我有一個情況我有一個文本文件中讀取字典中,從特定格式的另一個列表特定格式如何有通過列表追加多個值,目前我有一個問題,我無法通過正常</p> <p>認爲
(捕食)吃(獵物)
什麼,我試圖做的就是把它變成一本字典但有些情況下也有多個行的情況。
(捕食)吃(獵物)
如果同一捕食者顯示出來吃不同的獵物。
到目前爲止,這是什麼樣子......
import sys
predpraydic={}#Establish universial dictionary for predator and prey
openFile = open(sys.argv[1], "rt") # open the file
data = openFile.read() # read the file
data = data.rstrip('\n') #removes the empty line ahead of the last line of the file
predpraylist = data.split('\n') #splits the read file into a list by the new line character
for items in range (0, len(predpraylist)): #loop for every item in the list in attempt to split the values and give a list of lists that contains 2 values for every list, predator and prey
predpraylist[items]=predpraylist[items].split("eats") #split "eats" to retrive the two values
for predpray in range (0, 2): #loop for the 2 values in the list
predpraylist[items][predpray]=predpraylist[items][predpray].strip() #removes the empty space caued by splitting the two values
for items in range (0, len(predpraylist)
if
for items in range (0, len(predpraylist)): # Loop in attempt to place these the listed items into a dictionary with a key of the predator to a list of prey
predpraydic[predpraylist[items][0]] = predpraylist[items][1]
print(predpraydic)
openFile.close()
正如你看到的,我只是轉儲格式進我試圖轉換成一個字典的列表。
但是,這種方法只會接受一個值的關鍵。我想要的東西,有兩件事情就像
獅子吃斑馬 獅子吃狗
有一本字典是
獅:[「斑馬」,「狗」]
我不能想到這樣做的一種方式。任何幫助,將不勝感激。
哦,感謝上帝,我以爲我會發瘋。我使用了第一種方法,因爲這是一項大學任務,我不完全確定我是否可以依賴導入defaultdict。儘管我找到了我想要的東西,但很多謝謝。 – user1877961
+1。 @ user1877961歡迎來到SO!當像這樣的答案解決您的問題時,您可以單擊分數下方的空白複選標記以接受它。 – RocketDonkey