2017-05-12 72 views
0

代碼(不完全):多個列表與文件中的行Python中比較

list1 = ['1', '2', '3'] 
list2 = ['a', 'b', 'c'] 
list3 = ['12' '13' '14'] 
for list_in in list1: 
    with open("buffer_file") as f: 
     for line in f: 
      if len(line.split(" ")) >= 3: 
       var1 = line.split(" ") 
       if var1[0] == list1[0] and var[1] == list2[0] and var[3] == list3[0]: 

buffer_file

no 
priority enabled 
1 a 12 
2 b 13 
3 d 14 
pump it 

我試圖在這裏,如果在文件中的行和列表值匹配,然後打印文件行匹配。

實施例1:

list1[0], list2[0], list3[0] 

與線匹配包含1 a 12值,以便打印matched

實施例2:

list1[1], list2[1], list3[1] 

與行包含2 b 13值相匹配,以便打印matched

例3:

list1[2], list2[2], list3[2] 

是不匹配的,因爲行包含3 d 12值Print不匹配,也打印不匹配的元素就是d

任何一個請建議我什麼是完成這件事的最佳方法。我感到我的代碼中間。

+0

它不完整的代碼和檢查我的做法是正確的或有任何其他簡單的方法我能實現這個 – asteroid4u

+0

有什麼目的你列表的第二和第三個元素,你似乎沒有對他們做任何事情? – timgeb

+0

我們必須使用它們並用線條對每個元素進行驗證 – asteroid4u

回答

0

在這裏讀一下這幾行。基本上聽起來你想要忽略所有行不是三元組的行,列舉文件並在你的原始列表中找到匹配。

values = [ 
    ['1', '2', '3'], 
    ['a', 'b', 'c'], 
    ['12', '13', '14'], 
] 

def triples(line): 
    return len(line.split()) >= 3 


with open("test_file.txt") as f: 
    content = filter(triples, (map(str.strip, f.readlines()))) 
    # Loop over the file keeping track of index 
    for index, line in enumerate(content): 
     # Compare split line and triples 
     if line.split() == list(map(itemgetter(index), values)): 
      print(line) 

給我,其中「test_file.txt」包含您所列的輸入

1 a 12 
2 b 13 
1

您可以zip你的三個列表,以便你可以抓住並檢查它們的值作爲排列要素的三胞胎。

expected = zip(list1, list2, list3) 
print expected 
[ ('1', 'a', '12'), ('2', 'b', '13'), ... ] 

如果文件中的行列表元素一個匹配一個,然後你可以再通過期望值和實際值使用zip()循環在一起。 zip()是你的朋友。 (如果文件中有多餘的線條,使用一個變量來走三元組的列表。)

with open("buffer_file") as f: 
    for exp, actual in zip(expected, f): 
     if exp == actual.split(): # compares two 3-tuples 
      <etc.> 
+0

請注意,OP是使用Python 2.7,其中'zip'不返回迭代器。 – timgeb

+1

糟糕!感謝您的支持! – alexis