简体   繁体   English

如何在python中使用list comprehension从列表中获取元组

[英]how to get tuples from lists using list comprehension in python

I have two lists and want to merges them into one list of tuples . 我有两个列表,并希望将它们合并到一个tuples列表中。 I want to do it with list comprehension , I can get it working using map . 我想用list comprehension来做,我可以使用map来实现它。 but would be nice to know how list comprehension here will work. 但很高兴知道这里的列表理解是如何工作的。 code here 代码在这里

>>> lst =  [1,2,3,4,5]
>>> lst2 = [6,7,8,9,10]
>>> tup = map(None,lst,lst2) # works fine
>>> tup
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> l3 = [lst, lst2]
>>> l3
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
>>> zip(*l3) # works fine
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

>>> [(i,j) for i in lst and for j in lst2] # does not work
  File "<stdin>", line 1
    [(i,j) for i in lst and for j in lst2]
                              ^
SyntaxError: invalid syntax
>>> 

I have written comments where it works and where it does not. 我写了评论它在哪里工作,哪里没有。 How can a two for-loop be coupled in list comprehension 如何在list comprehension耦合两个for-loop

Think about list comprehensions as loops. 将列表推导视为循环。 How can you write 2 not nested loops? 你怎么写2而不是嵌套循环?

You can do this with somewhat wierd list comprehension: 你可以用一些奇怪的列表理解来做到这一点:

[(x, lst2[i]) for i, x in enumerate(lst)]

or 要么

[(lst[i], lst2[i]) for i in xrange(len(lst))]

But actually, it's better to use zip . 但实际上,使用zip更好。

The list comprehension way is silly, because it just wraps a do-nothing list comprehension around zip : 列表理解方式很愚蠢,因为它只包含一个无用的列表理解zip

[(i,j) for i, j in zip(lst, lst2)]

Just use zip , this is what it's for. 只需使用zip ,这就是它的用途。 There's no sense in forcing yourself to use list comprehensions when they don't accomplish anything. 强迫自己在没有完成任何事情时使用列表推导是没有意义的。

Edit: If your question is "how do I get two for loops in one list comprehension", you should ask that instead. 编辑:如果你的问题是“我如何在一个列表理解中得到两个for循环”,你应该问这个问题。 The answer is "You can't get two PARALLEL for loops in one list comprehension". 答案是“你不能在一个列表理解中得到两个PARALLEL for循环”。 Any time you put two for clauses in a list comprehension, they will be nested. 每当你在列表理解中放入两个for子句时,它们将被嵌套。 That, a list comprehension like this: 那个,列表理解是这样的:

[... for a in list1 for b in list2]

Works like two nested for loops: 像两个嵌套for循环一样工作:

for a in list1:
    for b in list2:
        ...

You can't write a list comprehension that does this: 你不能写一个列表理解来做到这一点:

for a in list1:
    ...
for b in list2:
    ...

. . . and you don't need to, because you have the zip function to do that instead. 并且你不需要,因为你有zip功能来代替。

(You can sort of fake it using a solution like @Roman Pekar's, but that doesn't really do two for loops; it just does one and uses the values from that one to reach into the other list.) (你可以使用像@Roman Pekar这样的解决方案来伪装它,但是它实际上没有两个for循环;它只做一个并使用那个中的值到达另一个列表。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM