首页 > 解决方案 > 为什么for循环中的if语句中的“不等于”(!=)只返回一行

问题描述

我有以下 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']

标签: pythoncsv

解决方案


x∧y的否定是(¬x)∨(¬y)。这意味着您需要用 替换andor例如:

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)

或者如果您不想使用德摩根定律[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)

推荐阅读