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