我希望我的字典具有檔案名 'hello.txt' 的值而不是數值 1。我的代碼是
file_list = [hello.txt, bye.txt, test.txt]
file_contents = ['text of hello', 'text of bye', 'text of test']
dict = {}
for i in range(len(file_list)):
check = file_contents[i].lower()
for item in words:
if item in check:
if item not in dict:
dict[item] = []
if item in dict:
dict[item].append(i 1)
dict = {k: list(set(v)) for k, v in dict.items()}
print(dict)
我目前得到的輸出是
{'test': [3], 'text': [1, 2, 3]}
但我希望它是
{'test': [test.txt], 'text': [hello.txt, bye.txt, test.txt]}
我將如何改變這一點?
uj5u.com熱心網友回復:
您可以附加檔案名,而不是將 i 1 附加到您的字典中,即 file_list[i]
dict[item].append(file_list[i])
請注意,您可能會遇到錯誤,因為您的檔案名沒有被引號括起來并且不被視為字串。改用這個:
file_list = ['hello.txt', 'bye.txt', 'test.txt']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336737.html
上一篇:如何使用一行選擇一個陣列中沒有出現在另一個陣列中的最小值?
下一篇:按交集合并2個組串列
