2015-04-06 46 views
0

中有什麼我有2個csv文件,我想比較其中之一是所有國家的主文件,然後是另一個只有少數幾個國家。這是一個試圖爲一些基本的測試中,我提出:比較python中的csv文件,看看在

char = {} 
with open('all.csv', 'rb') as lookupfile: 
    for number, line in enumerate(lookupfile): 
     chars[line.strip()] = number 

with open('locations.csv') as textfile: 
    text = textfile.read() 
    print text 
for char in text: 
    if char in chars: 
     print("Country found {0} found in row {1}".format(char, chars[char])) 

我試圖讓國家的主文件的最終輸出與指示次級柱,如果它在其他列表上來

謝謝!

回答

0

試試這個:

  • 寫一個函數打開CSV到包含每個國家的作爲密鑰的Python字典你在CSV中找到。它可以僅僅是這樣的:

{'US':True, 'UK':True}

  • 這樣做對雙方的CSV文件。
  • 現在,爲您正在比較的csv迭代dictionary.keys(),並檢查其他字典是否具有相同的密鑰。

這將是一個非常快速的算法,因爲字典給我們持續時間查找,和你有一個數據結構,它可以很容易地用它來看看你發現了哪些國家。

正如Eric在評論中提到的那樣,您還可以使用set membership來處理此問題。這實際上可能是更簡單,更好的方式來做到這一點:

set1 = set()     # A new empty set 
set1.add("country") 
if country in set: 
    #do something 
+0

當你需要毫無價值詞典,使用套... –

+0

林相當新的Python,所以我將不得不作出在csv文件的一切的關鍵像你已經顯示的變量一樣? – Gaddi

+0

如果你只是比較國家,那麼你只需要爲國家制作鑰匙。字典[國家] =真。 @EricLevieil集合的問題是查找的最壞情況是O(n)。 –

0

你可以使用完全相同的邏輯作爲原始循環:

with open('locations.csv') as textfile: 
    for line in textfile: 
     if char.strip() in chars: 
      print("Country found {0} found in row {1}".format(char, chars[char]))