一千萬個為什麽

搜索

對於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'

我將如何在代碼中寫這個?

最佳答案

  1. 編寫一個將類別名稱映射到文件名的字典。
  2. 遍歷您的類別列表,並使用類別名稱索引到dict中來檢索文件名。
  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

轉載註明原文: 對於python,我想讓列表中的每個值響應另一個值