【问题标题】:Why "not equal" (!=) in if statement within for loop returns only one row为什么for循环中的if语句中的“不等于”(!=)只返回一行
【发布时间】:2019-07-27 10:42:34
【问题描述】:

我有以下 csv 数据,我想过滤它以仅拉 8PM,apple,table

1,8PM,apple,table,yes
2,8PM,apple,table,no
3,6PM,carrot,chair,no
4,7PM,berries,table,no
5,8PM,apple,table,yes
6,6PM,banana,table,no
7,8PM,carrot,chair,no
8,7PM,carrot,table,no
9,8PM,guava,chair,no
10,7PM,guava,table,yes
11,8PM,apple,table,no

我尝试测试'==',

if each[1] == '8PM' and each[2] == 'apple' and each[3] == 'table':

它给出了预期的结果:

['1', '8PM', 'apple', 'table', 'yes']
['2', '8PM', 'apple', 'table', 'no']
['5', '8PM', 'apple', 'table', 'yes']
['11', '8PM', 'apple', 'table', 'no']

这是我正在使用的代码:

import csv
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    pool = list(reader)
    for each in pool:
        if each[1] != '8PM' and each[2] != 'apple' and each[3] != 'table':
            print(each)

对于实际结果,我只得到一行:

['3', '6PM', 'carrot', 'chair', 'no']

我期待以下内容:

['3', '6PM', 'carrot', 'chair', 'no']
['4', '7PM', 'berries', 'table', 'no']
['6', '6PM', 'banana', 'table', 'no']
['7', '8PM', 'carrot', 'chair', 'no']
['8', '7PM', 'carrot', 'table', 'no']
['9', '8PM', 'guava', 'chair', 'no']
['10', '7PM', 'guava', 'table', 'yes']

【问题讨论】:

  • 仅当第二列 not 8PM 等时。您可能希望将 and 替换为 or

标签: python csv


【解决方案1】:

x∧y的否定是(¬x)∨(¬y)。这意味着您需要将and 替换为or,例如:

import csv
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    pool = list(reader)
    for each in pool:
        if each[1] != '8PM' or each[2] != 'apple' or each[3] != 'table':
            print(each)

或者如果你不想使用de Morgan's laws [wiki],你可以简单地在前面使用not,比如:

import csv
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    pool = list(reader)
    for each in pool:
        if not (each[1] == '8PM' and each[2] == 'apple' and each[3] == 'table'):
            print(each)

【讨论】:

  • 第一个代码“!= '8PM' or”返回所有 11 行。而第二个返回了我的预期结果。感谢您的时间!
  • @orpheum:如果我在本地运行,第一行和第二行都会得到七行。
  • 你是对的@Willem。我再次运行它,得到了七行。我想我在第一次尝试时错过了一些东西。所以第一个和第二个都很完美。感谢您指出这一点并链接到德摩根定律。
猜你喜欢
  • 2021-04-16
  • 2022-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 2018-03-07
相关资源
最近更新 更多