Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么';Python列表理解和普通循环之间的区别是什么?_Python - Fatal编程技术网

什么';Python列表理解和普通循环之间的区别是什么?

什么';Python列表理解和普通循环之间的区别是什么?,python,Python,下一个循环返回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 我哪里出错了 试试这个- count += len([line for line

下一个循环返回
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
我哪里出错了

试试这个-

count += len([line 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只执行一次。

这是因为在第二种情况下,if条件只执行一次

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


这里列表对象不是None,因此count+=1执行一次。

列表理解是创建列表的快捷方式。以下(大致)相当:

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])

列表理解是创建列表的快捷方式。以下(大致)相当:

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])

仅供参考,这叫列表理解,不是单行循环。仅供参考,这叫列表理解,不是单行循环。