python中for循环中的[]括号是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30670310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:48:23  来源:igfitidea点击:

What do [] brackets in a for loop in python mean?

python

提问by Mo.

I'm parsing JSON objects and found this sample line of code which I kind of understand but would appreciate a more detailed explanation of:

我正在解析 JSON 对象,并找到了这行代码示例,我有点理解但希望对以下内容进行更详细的解释:

for record in [x for x in records.split("\n") if x.strip() != '']:

I know it is spliting records to get individual records by the new line character however I was wondering why it looks so complicated? is it a case that we can't have something like this:

我知道它正在拆分记录以通过换行符获取单个记录,但是我想知道为什么它看起来如此复杂?是不是我们不能有这样的事情:

for record in records.split("\n") if x.strip() != '']:

So what do the brackets do []? and why do we have x twice in x for x in records.split....

那么括号 [] 有什么作用呢?为什么我们有两次 xx for x in records.split....

Thanks

谢谢

采纳答案by folkol

The "brackets" in your example constructs a new list from an old one, this is called list comprehension.

您示例中的“括号”从旧列表构建了一个新列表,这称为列表理解

The basic idea with [f(x) for x in xs if condition]is:

基本思想[f(x) for x in xs if condition]是:

def list_comprehension(xs):
    result = []
    for x in xs:
        if condition:
            result.append(f(x))
    return result

The f(x)can be any expression, containing xor not.

f(x)可以是任何表达式,含有x或没有。

回答by Zizouz212

That's a list comprehension, a neat way of creating lists with certain conditions on the fly.

这是一种列表理解,一种即时创建具有特定条件的列表的巧妙方法。

You can make it a short form of this:

你可以把它变成一个简短的形式:

a = []
for record in records.split("\n"):
    if record.strip() != '':
        a.append(record)

for record in a:
    # do something

回答by uniqueusername

The square brackets ( [] ) usually signal a list in Python.

方括号 ( [] ) 通常表示 Python 中的列表。