简体   繁体   English

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

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

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....以及为什么我们有 x 两次在x for x in records.split....

Thanks谢谢

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 x or not. f(x)可以是任何表达式,包含或不包含x

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

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

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

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