我是python的新手,需要将列表转换为字典。我知道我们可以将元组列表转换为字典。
这是输入列表:
L = [1,term1, 3, term2, x, term3,... z, termN]
我希望将此列表转换为元组列表(或字典),如下所示:
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
我们怎样才能轻松实现python?
答案 0 :(得分:83)
>>> 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')]
您想一次分组三个项目吗?
>>> zip(it, it, it)
您想一次分组N个项目吗?
# 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)
答案 1 :(得分:12)
尝试使用群组群集习语:
zip(*[iter(L)]*2)
来自https://docs.python.org/2/library/functions.html:
保证了迭代的从左到右的评估顺序。 这使得将数据序列聚类成成语成为可能 使用zip(* [iter(s)] * n)的n长度组。
答案 2 :(得分:7)
使用zip
直接列入字典以配对连续的偶数和奇数元素:
m = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
d = { x : y for x, y in zip(m[::2], m[1::2]) }
或者,因为你熟悉元组 - > dict指示:
d = dict(t for t in zip(m[::2], m[1::2]))
甚至:
d = dict(zip(m[::2], m[1::2]))
答案 3 :(得分:5)
使用切片?
L = [1, "term1", 2, "term2", 3, "term3"]
L = zip(L[::2], L[1::2])
print L
答案 4 :(得分:3)
[(L[i], L[i+1]) for i in xrange(0, len(L), 2)]
答案 5 :(得分:2)
试试这个,
>>> 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')]
>>>
>>> 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')]
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
>>> map(None,*[iter(L)]*2)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
>>>
答案 6 :(得分:1)
下面的代码将处理偶数和奇数大小的列表:
[set(L[i:i+2]) for i in range(0, len(L),2)]