可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
>>> 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)
回答2:
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).
回答3:
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]))
回答4:
Using slicing?
L = [1, "term1", 2, "term2", 3, "term3"] L = zip(L[::2], L[1::2]) print L
回答5:
[(L[i], L[i+1]) for i in xrange(0, len(L), 2)]
回答6:
Try this ,
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] >>> it = iter(L) >>> [(x, next(it)) for x in it ] [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')] >>>
OR
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] >>> [i for i in zip(*[iter(L)]*2)] [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
OR
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] >>> map(None,*[iter(L)]*2) [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')] >>>