尝试以下方法:import csv
file_1_tuples = []
with open("file_1.csv") as fh:
csv_reader = csv.reader ( fh )
for row in csv_reader:
file_1_tuples.append( tuple(row) )
with open("file_2.csv") as fh:
csv_reader = csv.reader ( fh )
for row in csv_reader:
if tuple(row[0:3]) in file_1_tuples:
print ( row[3:6] )
使用以下数据运行时:
file_1.csvperson, john, smith
person, anne, frank
person, bob, macdonald
fruit, orange, banana
fruit, strawberry, fields
fruit, ringring, banana
file_2.csvperson, john, smith, 1, 2, 3
person, anne, frank, 4, 5, 6
person, bob, macdonald, 7, 8, 9
它产生输出[' 1', ' 2', ' 3']
[' 4', ' 5', ' 6']
[' 7', ' 8', ' 9']
编辑:使用集合和列表理解