对于python我想使列表中的每个值都对应另一个值
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我想使列表中的每个值都对应另一个值
- 编写一个将类别名称映射到文件名的字典。
- 循环访问类别列表,并通过使用类别名称将字典索引到字典中来检索文件名。
- 使用
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
它看起来像你可以简单地通过添加'.txt'到所有键来构建字典。所以''字典((我,'%s.txt'%i)'['电影','体育',...)' – 2011-05-28 14:34:32
@ bradley。只是想知道传球是什么意思?还有它的问题,该文件被打开data_entry功能内?.. IDN,如果你会得到我的意思哈哈 – Alana 2011-05-28 14:42:59
Alana,什么都没有。 – 2011-05-28 14:44:32
也许你想要一本字典/哈希:
dic = { 'movies':'movies.txt', 'xxx':'xxx.txt' }
for key,value in dic.items():
print (key, value)
'for',而不是'foreach'。你也可以同时迭代键和值:'for k,v in dic.values():print(k,v)' – 2011-05-28 14:36:30
@Steve Howard我认为你的意思是dic.items()? – 2011-05-28 14:58:22
我做到了。我在解释器中使用它的时候固定了它,然后发布了错误的东西。 ;) – 2011-05-28 19:02:12
如果你的文本文件的名称总是要<categoryname>.txt
我只想做:
for category in categories:
with open(category + ".txt", 'r') as f:
# Do whatever you need to here...
pass
这当然不需要di军团或其他任何东西。如果每个类别的文件名称可能会改变,那么我建议使用字典。
'file_names = dict((x,x +'.txt')for data_entry)'? – 2011-05-28 14:32:50