python中for循环中的[]括号是什么意思? [英] What do [] brackets in a for loop in python mean?

查看:105
本文介绍了python中for循环中的[]括号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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() != '']:

那么括号 [] 的作用是什么?以及为什么我们在 x for x in records.split .....

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

谢谢

推荐答案

示例中的括号"从旧列表构建新列表,称为 列表理解.

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

[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

f(x) 可以是任何表达式,包含或不包含 x.

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

这篇关于python中for循环中的[]括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆