2011-05-28 93 views
0
def data_entry(categories): 

# these are the values within categories 
data_entry(['movies', 'sports', 'actors', 'tv', 'games', \ 
    'activities', 'musicians', 'books']) 

# for each different value in categories i need it to open a different txt file 
# for example 
when categories = movies ([0]) 
filename='movies.txt' 

when categories = sports([1]) 
filename='sports.txt' 

我該如何在代碼中編寫這個代碼?對於python我想使列表中的每個值都對應另一個值

+2

'file_names = dict((x,x +'.txt')for data_entry)'? – 2011-05-28 14:32:50

回答

3
  1. 編寫一個將類別名稱映射到文件名的字典。
  2. 循環訪問類別列表,並通過使用類別名稱將字典索引到字典中來檢索文件名。
  3. 使用open()與文件名。

例子:

categories = ["movies", "tv"] 

# long winded: 
filenames = { 
    "movies": "movies.txt", 
    "tv": "television.txt", 
    # ... 
} 

# alternatively: 
filenames = dict([(x, x + ".txt") for x in categories]) 

for category in categories: 
    with open(filenames[category], 'rb'): 
     pass 
+1

它看起來像你可以簡單地通過添加'.txt'到所有鍵來構建字典。所以''字典((我,'%s.txt'%i)'['電影','體育',...)' – 2011-05-28 14:34:32

+0

@ bradley。只是想知道傳球是什麼意思?還有它的問題,該文件被打開data_entry功能內?.. IDN,如果你會得到我的意思哈哈 – Alana 2011-05-28 14:42:59

+0

Alana,什麼都沒有。 – 2011-05-28 14:44:32

1

也許你想要一本字典/哈希:

dic = { 'movies':'movies.txt', 'xxx':'xxx.txt' } 
for key,value in dic.items(): 
    print (key, value) 
+1

'for',而不是'foreach'。你也可以同時迭代鍵和值:'for k,v in dic.values():print(k,v)' – 2011-05-28 14:36:30

+0

@Steve Howard我認爲你的意思是dic.items()? – 2011-05-28 14:58:22

+0

我做到了。我在解釋器中使用它的時候固定了它,然後發佈了錯誤的東西。 ;) – 2011-05-28 19:02:12

3

如果你的文本文件的名稱總是要<categoryname>.txt我只想做:

for category in categories: 
    with open(category + ".txt", 'r') as f: 
     # Do whatever you need to here... 
     pass 

這當然不需要di軍團或其他任何東西。如果每個類別的文件名稱可能會改變,那麼我建議使用字典。

相關問題