Convert List to a list of tuples python

I am newbie to python and need to convert a list to dictionary. I know that we can convert list of tuples to dictionary.

This is the input list:

L = [1,term1, 3, term2, x, term3,... z, termN]

and I want to convert this list to a list of tuples (OR to a dictionary) like this:

[(1, term1), (3, term2), (x, term3), ...(z, termN)]

How can we do that easily python?


>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]

You want to group three items at a time?

>>> zip(it, it, it)

You want to group N items at a time?

# Create N copies of the same iterator
it = [iter(L)] * N
# Unpack the copies of the iterator, and pass them as parameters to zip
>>> zip(*it)

Try with the group clustering idiom:

zip(*[iter(L)]*2)

From https://docs.python.org/2/library/functions.html:

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).


List directly into a dictionary using zip to pair consecutive even and odd elements:

m = [ 1, 2, 3, 4, 5, 6, 7, 8 ] 
d = { x : y for x, y in zip(m[::2], m[1::2]) }

or, since you are familiar with the tuple -> dict direction:

d = dict(t for t in zip(m[::2], m[1::2]))

even:

d = dict(zip(m[::2], m[1::2]))
链接地址: http://www.djcxy.com/p/24030.html

上一篇: 如何将一个字符串分割成一个列表?

下一篇: 将列表转换为元组列表python