Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.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_List_Filter_List Comprehension - Fatal编程技术网

Python 过滤和列表理解的区别

Python 过滤和列表理解的区别,python,list,filter,list-comprehension,Python,List,Filter,List Comprehension,我使用的是Python3,我的问题是为什么输出不同 print([x * x for x in range(2, 5, 2) if x % 4 == 0]) # returns [16] q = [x * x for x in range(2, 5, 2)] print(list(filter(lambda x: x % 4 == 0, q))) # returns [4, 16] 在前者中,[2,4]中的每一项都会根据x%4==0进行检查。在后者中,filter将lambda应用于q中的每

我使用的是Python3,我的问题是为什么输出不同

print([x * x for x in range(2, 5, 2) if x % 4 == 0]) # returns [16]

q = [x * x for x in range(2, 5, 2)]
print(list(filter(lambda x: x % 4 == 0, q))) # returns [4, 16]

在前者中,
[2,4]
中的每一项都会根据
x%4==0
进行检查。在后者中,
filter
将lambda应用于
q
中的每个项目,这不是
[2,4]
,而是
[4,16]
。因此,
x%4==0
两次返回true

print(([x * x for x in range(2, 5, 2) if x % 4 == 0]))
在这里,
范围
计算为[2,4],只有
[4]
能够通过if条件

q = ([x * x for x in range(2, 5, 2)])
print(list(filter(lambda x: x % 4 == 0, q)))

这里,
q
包含每个元素的
x*x
,因此列表是
[2*2,4*4]=[4,16]
,这两个元素都通过过滤器选择器,因为
q
包含正方形

并且
lambda x:x%4==0
将为这两个变量返回
True

In [3]: 4 % 4 == 0
Out[3]: True

In [4]: 16 % 4 == 0
Out[4]: True
执行检查后的列表编号,检查失败2次(2%4为2):

因此,2*2=4将不包括在列表中

简而言之,如果您希望获得相同的行为,请在计算余数之前将列表理解修改为平方数:

[x * x for x in range(2, 5, 2) if pow(x, 2, 4) == 0] # [4, 16]
#                                   ↖ equivalent to (x ** 2) % 4
In [5]: 2 % 4 == 0
Out[5]: False
[x * x for x in range(2, 5, 2) if pow(x, 2, 4) == 0] # [4, 16]
#                                   ↖ equivalent to (x ** 2) % 4