繁体   English   中英

Python列表理解和普通循环之间有什么区别?

[英]What's the difference between Python list comprehension and normal loop?

下一个循环为count参数返回值3

for line in textfile.text.splitlines():
    count += 1 if 'hostname' in line else 0

但是,尝试使用列表推导执行相同操作会返回1

count += 1 if ['hostname' in line for line in textfile.text.splitlines()] else 0

我哪里做错了?

列表理解是创建列表的捷径。 以下(大致)等效:

result = []
for item in l:
    if condition(item):
        result.append(item.attribute)

result = [item.attribute for item in l if condition(item)]

所以你的代码

count += 1 if ['hostname' in line for line in textfile.text.splitlines()] else 0

将与

result = []
for line in textfile.text.splitlines():
    result.append('hostname' in line)

count += 1 if result else 0

这显然与

for line in textfile.text.splitlines():
    count += 1 if 'hostname' in line else 0

相反,你可以做类似的事情

count += sum([1 for line in textfile.text.splitlines() if 'hostname' in line])

尝试这个 -

count += len([line for line in textfile.text.splitlines() if 'hostname' in line])

这是因为在第二种情况下,您的if条件仅执行一次。

如果listobject否则为0,则第二条语句转换为count + = 1;

这里的列表对象不是None,所以count + = 1执行一次。

暂无
暂无

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

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