[英]Iterating through dictionary and printing matching rows from tsv file
我有一個這樣的tsv文件與標題。
Header1 header2 header3 header4 header5
Aa bb dd cc aa
Bb bb aa cc bb
Cc bb cc dd aa
Aa bb ee cc dd
Aa vv ff gg ii
我有一個字典,如{'0': 'aa', '1':'bb','3':'cc'}
我應該解析這個文件,並返回文件中的行,其中索引0的每列是aa,索引1是bb,索引3是cc。 換句話說,我需要得到第一列為aa,第二列為bb,第四列為cc的所有行。 所以我應該能夠從tsv文件中打印第一行和第四行,這些行是
Aa bb dd cc aa
Aa bb ee cc dd
我的代碼片段沒有給出所有這些條件的交集,而是給出了每個條件滿足的所有行。 請幫我糾正我的腳本。 上面指定的字典被命名為索引字典。
data=csv.reader(open(tsvfile,'rb'),delimiter = "\t")
fields =data.next()
print "-------------------------Rows Filtered-------------------------"
for key,value in indexdict.items():
for row in data:
if row[key]== value:
linecount=linecount+1
print row`
all
內置功能都是您所需要的:
for row in data:
if all(row[key] == value for key, value in indexdict.items()):
print row
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.