Convert List to a list of tuples python

匿名 (未验证) 提交于 2019-12-03 02:47:02

问题:

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')] >>>  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!