过滤奇数

发布于 2024-08-10 11:36:15 字数 193 浏览 8 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゝ杯具 2024-08-17 11:36:15

该代码所做的正是您所期望的 - 如果第二项是偶数,则将其加一并将其放入列表中。

因此,对于第一行,它认为 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.

装纯掩盖桑 2024-08-17 11:36:15

我相信您需要将比较从 == 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.

隱形的亼 2024-08-17 11:36:15

您正在测试 row[1]%2,但正在打印 row[1]+1
因此,当 row[1]==2 时,它是偶数,但您要将 3 附加到结果
row[1]==5时,它是奇数,所以你将其过滤掉
row[1]==8 时,它是偶数,但您将 9 附加到结果中

You are testing row[1]%2, but printing row[1]+1
so when row[1]==2, it is even, but you are appending 3 to the result
when row[1]==5, it is odd, so you filter it out
and when row[1]==8, it is even, but you are appending 9 to the result

家住魔仙堡 2024-08-17 11:36:15
M = [[1,2,3],
    [4,5,6],
    [7,8,9]]
col2 = []

for row in M:
    if row[1]%2 == 1:
        col2.append(row[1])
print col2
M = [[1,2,3],
    [4,5,6],
    [7,8,9]]
col2 = []

for row in M:
    if row[1]%2 == 1:
        col2.append(row[1])
print col2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文