【问题标题】:list iteration with 'i for j in' that I never saw [duplicate]列出我从未见过的'i for j in'的迭代[重复]
【发布时间】:2014-04-06 12:41:09
【问题描述】:

我正在尝试了解以下 python 代码的作用

plain_list = [ j for i in arguments for j in i ]

我从来没有见过这样的语法,有人可以帮帮我吗?

【问题讨论】:

  • 这叫做列表推导。知道这一点,你应该可以查到它。
  • 请注意,这是扁平化列表列表(iterable of iterables)的一个相对常见的习惯用法,经常被那些倾向于不为所有内容导入itertools 的人使用(itertools.chain 可用于同样的结局。)
  • OP:欢迎来到 Python,做任何事情的第一步是“我怎样才能将其简化为列表理解?”然后第二步是“哦,这太荒谬了,我应该改用itertools。”

标签: python


【解决方案1】:

它被称为list comprehension

使用普通的 for 循环,其等效代码为:

plain_list = []               # Make a list plain_list
for i in arguments:           # For each i in arguments (which is an iterable)
    for j in i:               # For each j in i (which is also an iterable)
        plain_list.append(j)  # Add j to the end of plain_list

下面是它用于展平列表列表的演示:

>>> arguments = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>
>>> plain_list = [ j for i in arguments for j in i ]
>>> plain_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> plain_list = []
>>> for i in arguments:
...     for j in i:
...         plain_list.append(j)
...
>>> plain_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 1970-01-01
    • 2017-10-30
    • 2019-06-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多