1

我目前遇到了一个我无法正确思考的问题

我有一个以特定格式读取的文本文件的情况

(捕食者)吃(猎物)

我正在尝试做的是将它放入字典中,但是在某些情况下存在多行。

(捕食者)吃(猎物)

同一个捕食者出现吃不同的猎物。

到目前为止,这就是它的样子......

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() 

如您所见,我只是将格式转储到我尝试转换为字典的列表中。

但是这种方法只接受一个键值。我想要有两件事的东西

狮子吃斑马 狮子吃狗

有一本字典

狮子:['斑马','狗']

我想不出这样做的方法。任何帮助,将不胜感激。

4

1 回答 1

2

有两种合理的方法可以制作包含您添加到的列表而不是单个项目的字典。第一个是在添加新值之前检查现有值。第二种是使用更复杂的数据结构,它负责在必要时创建列表。

这是第一种方法的快速示例:

predpreydic = {}

with open(sys.argv[1]) as f:
    for line in f:
        pred, eats, prey = line.split() # splits on whitespace, so three values
        if pred in predpreydic:
            predpreydic[pred].append(prey)
        else:
            predpreydic[pred] = [prey]

第一种方法的变体用字典上稍微更微妙的方法调用替换了if/块:else

        predpreydic.setdefault(pred, []).append(prey)

如果该方法不存在,则该setdefault方法设置为一个空列表,然后返回该值(新的空列表或先前的现有列表)。predpredic[pred]它的工作方式与解决问题的另一种方法非常相似,这是接下来的问题。

我提到的第二种方法涉及模块中defaultdictcollections(Python 标准库的一部分)。这是一个字典,每当您请求一个尚不存在的键时,它都会创建一个新的默认值。为了按需创建值,它使用您在首次创建defaultdict.

这是您的程序使用它的样子:

from collections import defaultdict

predpreydic = defaultdict(list) # the "list" constructor is our factory function

with open(sys.argv[1]) as f:
    for line in f:
        pred, eats, prey = line.split()
        predpreydic[pred].append(prey) #lists are created automatically as needed
于 2012-12-05T07:00:11.493 回答