过滤奇数
M = [[1,2,3],
[4,5,6],
[7,8,9]]
col2 = [row[1] + 1 for row in M if row[1] % 2 == 0]
print (col2)
输出:[3, 9]
我希望它能过滤掉奇数,但它的作用恰恰相反。
M = [[1,2,3],
[4,5,6],
[7,8,9]]
col2 = [row[1] + 1 for row in M if row[1] % 2 == 0]
print (col2)
Output: [3, 9]
I'm expecting it to filter out the odd numbers, but it does the opposite.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该代码所做的正是您所期望的 - 如果第二项是偶数,则将其加一并将其放入列表中。
因此,对于第一行,它认为 2 % 2 == 0 为 True,并设置 col2[0] = 2 + 1 = 3。对于第二行,5 % 2 == 0 为 False。对于第三行,8%2 == 0 为 True,并且 col2[1] = 8 + 1 = 9。
The code is doing exactly what you would expect - if the second item is even, increase it by one and put it into the list.
So for the first row, it sees that 2 % 2 == 0 is True, and sets col2[0] = 2 + 1 = 3. For the second row, 5 % 2 == 0 is False. For the third row, 8%2 == 0 is True, and col2[1] = 8 + 1 = 9.
我相信您需要将比较从
== 0
切换到== 1
。任何数除以2的模都是0或1,奇数时为1。
I believe you need to switch the comparison to
== 1
from== 0
.The modulus of any number divided by 2 is 0 or 1, 1 when it is odd.
您正在测试
row[1]%2
,但正在打印row[1]+1
因此,当
row[1]==2
时,它是偶数,但您要将3
附加到结果当
row[1]==5
时,它是奇数,所以你将其过滤掉当
row[1]==8
时,它是偶数,但您将9
附加到结果中You are testing
row[1]%2
, but printingrow[1]+1
so when
row[1]==2
, it is even, but you are appending3
to the resultwhen
row[1]==5
, it is odd, so you filter it outand when
row[1]==8
, it is even, but you are appending9
to the result