我目前遇到一个无法正确思考的问题
我遇到了一种情况,我正在以特定格式读取文本文件
(捕食者)吃掉(猎物)
我试图做的是将其放入字典中,但是在某些情况下会有多行。
(捕食者)吃掉(猎物)
同一个捕食者出现并吃掉不同的猎物。
到目前为止,这就是它的样子......
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()
如您所见,我只是将格式转储到一个列表中,然后尝试将其转换为字典。
但是这个方法只接受一个键值。我想要有两个东西的东西,比如
狮子吃掉斑马 狮子吃狗
拥有一本字典
狮子:['斑马','狗']
我想不出一种方法来做到这一点。任何帮助将不胜感激。
最佳答案
有两种合理的方法可以创建包含您添加到的列表而不是单个项目的字典。第一个是在添加新值之前检查现有值。第二个是使用更复杂的数据结构,它负责在需要时创建列表。
这是第一种方法的简单示例:
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
block :
predpreydic.setdefault(pred, []).append(prey)
setdefault
方法将 predpredic[pred]
设置为空列表(如果尚不存在),然后返回该值(可以是新的空列表,也可以是以前的现有列表)。它的工作原理与解决该问题的另一种方法非常相似,即接下来的方法。
我提到的第二种方法涉及 the defaultdict
class来自 collections
模块(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
关于python - 如何拥有一个字典,通过列表从另一个特定格式的列表附加多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13717117/