【问题标题】:List comprehension interpretation order while turning list of tuples into a list将元组列表转换为列表时的列表理解解释顺序
【发布时间】:2014-09-03 01:50:15
【问题描述】:

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

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) 这是将元组列表转换为列表的正确 Python 方法吗?

【问题讨论】:

    标签: python tuples list-comprehension


    【解决方案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”。

    【讨论】:

      【解决方案2】:
      1. 如果您删除部分 for y in x,那么剩下的部分:y for x in lot - y 未定义!

      2. 是的,使用列表推导被认为是非常“pythonic”:)

      【讨论】:

        【解决方案3】:

        2,是的。但也许你喜欢这个list(chain(*lot)),我认为它更好,虽然不是那么 Pythonic。 因为不需要 x 和 y 作为 temp var,而且更紧凑。

        【讨论】:

          【解决方案4】:

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

          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      
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-12-19
            • 2012-06-05
            • 1970-01-01
            • 2022-09-27
            • 1970-01-01
            • 2016-09-28
            相关资源
            最近更新 更多