我是Python的新手,需要将列表转换为字典。我知道我们可以将元组列表转换为字典。
这是输入列表:
L = [1,term1, 3, term2, x, term3,... z, termN]
并且我想将此列表转换为元组列表(或直接转换为字典),如下所示:
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
我们如何在Python中轻松做到这一点?
>>> 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)