python - 为什么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']
解决方案
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)
或者如果您不想使用德摩根定律[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)
推荐阅读
- python-2.7 - Odoo Python 2.7 编码 utf8
- mysql - 如何将这 2 个 SQL 查询合二为一
- ecmascript-next - “关系最小”是什么意思?
- .net-core - Azure Pipelines 中的 dotnet restore 任务突然开始使用 .NET core 3.0 SDK,而不是 2.2,破坏了我的管道
- laravel - Laravel 分页不显示 json 响应中的元数据
- python - 将 DataFrame 输出到 CSV 时标题的顺序一致
- ruby - 机械化超时
- python - 当我尝试分配给一个列表时,为什么每个列表值都会改变?
- java - 我收到此代码的堆栈溢出错误:
- java - 编写一个主要方法来调用一个对象?