将List转换为元组python列表

44 python tuples list

我是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)

  • @ user1717828每次访问迭代器时它都会前进位置.Zip正在配对两件事,取自这里的同一个迭代器.如果你写了`zip(iter(L),iter(L),iter(L))`它会这样做,但是通过打破iter创建并分享它你会得到这种行为. (3认同)
  • 有人可以解释一下“zip”在这种情况下在做什么吗?我以为我理解它是如何工作的,但显然不明白,因为这不会给出 `[(1,1,1),('term1','term1','term1'),...]` (2认同)
  • 这在 python2 中有效,但在 python3 中,您实际上需要将“zip”对象放入“list”中,如下所示:“list(zip(it,it))”,因为 python3 不会评估“zip”,除非您明确要求 - 请参阅 /sf/answers/1384434971/ (2认同)

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长度组的习惯成为可能.


per*_*eal 8

直接列入字典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)


vel*_*lis 5

使用切片?

L = [1, "term1", 2, "term2", 3, "term3"]
L = zip(L[::2], L[1::2])

print L
Run Code Online (Sandbox Code Playgroud)


Nis*_*ede 5

尝试这个 ,

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