【发布时间】: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。