我是Python新手。 有没有办法搜索另一个列表(csv表)中的值列表(单词和帧),只获取匹配的行?
示例:
LiastOfValues = ['吸烟''吸烟者','酗酒']
ListfromCSV = ID,TYPE,STRING1,NUMBER 1, a,'this is hard smoker man',4 2, b,'this one likes to drink',5 3, c,'dont like sigarets',6 4, e,'this one is smoking',7
在每行中搜索LiastOfValues并仅回复匹配的行。
The Output:
Output= ID,TYPE,STRING1,NUMBER 1, a,'this is hard smoker man',4 4, e,'this one is smoking',7
I have tryed this:
import csv ListfromCSV ="ListfromCSV.txt" LiastOfValues=['smoking','hard smoker','alcoholic','smoker'] with open(ListfromCSV ,'r') as f: LineReader=csv.reader(f,delimiter=',') for i in LineReader: if value in (i[2])) : print (i)
答案 0 :(得分:1)
试试这个。它假定您的csv不是嵌套的并且包含字符串。如果它是嵌套的,您可以将列表转换为字符串:
[row for row in csv if any(map(lambda x: x in row,LiastOfValues))]
此代码应获取具有匹配行的列表(除非您匹配,否则不包括标题)