将元组列表转换为列表时列出理解解释顺序

时间:2014-09-03 01:50:16

标签: python tuples list-comprehension

让我们假设 我有一个元组列表,如:

lot = [ (a,b),(c,d) ]

我希望将其转换为以下列表:

[a,b,c,d]

浏览stackoverflow后,我发现以下代码可以完成我想要做的事情:

mylist = [y for x in lot for y in x ]

问题:

1)如果我取出for y in x部分,代码怎么会中断?我想我的问题是如何解释列表理解中的条款

2)这是将元组列表转换为列表的正确pythonic方法吗?

4 个答案:

答案 0 :(得分:1)

  1. 如果您移除了部分for y in x,那么在左边的内容中:y for x in lot - y未定义!

  2. 是的,使用列表理解被认为非常“pythonic”#39; :)

答案 1 :(得分:1)

2,是的。但也许你喜欢这个list(chain(*lot)),我觉得它更好,尽管不是那么pythonic。 因为不需要x和y作为临时变量,而且更加紧凑。

答案 2 :(得分:1)

阅读理解的一种更简单的方法是在没有理解的情况下思考解决方案。你会这样做:

>>> lot = [ ('a','b'),('c','d') ]
>>> result = []
>>> for a_tuple in lot:
...     for item in a_tuple:
...             result.append(item)
...
>>> result
['a', 'b', 'c', 'd']

如果列表推导涉及两个循环,您只需编写循环的顺序,就像上面的“非列表理解”解决方案一样,但都在一行中:

>>> result = [item for a_tuple in lot for item in a_tuple]
>>> result
['a', 'b', 'c', 'd']

这应该回答为什么如果你取消第二个循环代码中断的原因。是的,使用列表推导被认为是“pythonic”。

答案 3 :(得分:1)

嵌套列表推导从左到右循环:

mylist = [y for x in lot for y in x ]
            ^^^^^^^^^^^^ this iterates through lot
                         e.g. x = ('a','b'), then x = ('c','d')


mylist = [y for x in lot for y in x ]
                         ^^^^^^^^^^ this iterates through each element in the tuple x
                                    since x = ('a', 'b'), y = 'a', then y = 'b', etc

mylist = [y for x in lot for y in x ]
          ^ this is the output

所以在上面的例子中:

    x   | y | output
--------|---|--------
 (a, b) | a | a      
 (a, b) | b | b      
 (c, d) | c | c      
 (c, d) | d | d      
相关问题