2024-03-29 11:14:04 发布
网友
我是python新手,需要将列表转换为字典。我知道我们可以把元组列表转换成字典。
这是输入列表:
L = [1,term1, 3, term2, x, term3,... z, termN]
我想把这个列表转换成一个元组列表(或字典),如下所示:
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
我们怎么能这么容易做到python?
尝试使用组群集习惯用法:
zip(*[iter(L)]*2)
来自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).
使用zip将连续的偶数和奇数元素配对,直接列出到字典中:
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]))
>>> 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)
尝试使用组群集习惯用法:
来自https://docs.python.org/2/library/functions.html:
使用
zip
将连续的偶数和奇数元素配对,直接列出到字典中:或者,因为您熟悉元组->;dict方向:
甚至:
你想一次分三组吗?
一次要对N个项目进行分组?
相关问题 更多 >
编程相关推荐