如何将列表值与单个 csv 文件行匹配?

How can I match a list value to a single cvs file's row?

我需要将整数值列表与 CVS 文件中的一行进行比较,以便找到与该值匹配的行。

'''

firstScore = 90  
secondScore = 80  
thirdScore = 75  

list = [firstScore, secondScore, thirdScore]

'''

csv 数据为:

    Name,first,second,third
    Paul,40,60,30
    Kevin,90,80,75
    Jenny,80,75,90

实际输出应该是匹配3个值的名字:Kevin.

由于缺少您的代码,我假设您使用 pandas 包和 read_csv 来使用上面给出的数据创建数据框 (df)。如果是这样,您可以使用以下命令从您的 df 中检索数据:

 df.loc[(df['first'] == list[0]) & (df['second'] == list[1]) & (df['third'] == list[2])].iloc[:,0]

我不清楚你的数据来自哪里,但这段代码应该涵盖了关键逻辑:

import io

data = '''
[Name, first, second, third]
[Paul, 40, 60, 30]
[Kevin, 90, 80, 75]
[Jenny, 80, 75, 90]
'''

lstFind = [str(x) for x in [90, 80, 75]] # convert to string fields

lstAll = []

f = io.StringIO(data)  # load string data as file text
for row in f: 
  if not row.strip(): continue # skip empty rows
  rowlst = row.strip().replace(" ","")[1:-1].split(",") # convert row to list
  lstAll.append(rowlst) # add to main list

for lst in lstAll:  # each list 
   if lst[1:] == lstFind:
      print(lst[0])    # Kevin

  

感谢 Handler (https://whosebug.com/users/9659528/handler ) 在这个问题关闭时解决了这个问题。 ''' 导入 csv

list = [firstScore, secondScore, thirdScore]

with open('test.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',')

# skip the header of your csv
next(reader)

for row in reader:
  if((list[0] == int(row[1])) and (list[1] == int(row[2])) and (list[2] == int(row[3]))):
    # print name (present in first column -> index 0 of the row) 
    print(row[0])
    break
  else:
    print("No match found..")

'''