我尝试将带有列表的文本文件放入其中,然后将输入值排列在" Height"意思是任何只吃生产者的动物的身高都是1。
我认为我对如何解决这个问题的理解很少:
a
p
,a
捕食
非常感谢任何帮助。我希望自己没有过于罗嗦或混淆我的信息
foodweb = {}
with open('AquaticFoodWeb.txt') as input:
for line in input:
animal, prey = line.strip().split(' eats ')
foodweb.setdefault(animal, []).append(prey)
print ("Predators and Prey:")
for animal, prey in sorted(foodweb.items()):
if len(prey) > 1:
print ("{} eats {} and {}".format(animal, ", ".join(prey[:-1]), prey[-1]))
else:
print ("{} eats {}".format(animal, ", ".join(prey)))
#Apex
values = [item.strip() for sub in foodweb.values() for item in sub]
for apex in foodweb.keys():
if apex.strip() not in values:
print("Apex Predators: ", apex)
这是文本文件输入:
Bird eats Prawn
Bird eats Mussels
Bird eats Crab
Bird eats Limpets
Bird eats Whelk
Crab eats Mussels
Crab eats Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab
Lobster eats Mussels
Lobster eats Limpets
Lobster eats Whelk
Mussels eats Phytoplankton
Mussels eats Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets
Whelk eats Mussels
Zooplankton eats Phytoplankton
输出需要:
Heights:
Bird: 4
Crab: 3
Fish: 3
Limpets: 1
Lobster: 4
Mussels: 2
Phytoplankton: 0
Prawn: 2
Seaweed: 0
Whelk: 3
Zooplankton: 1
答案 0 :(得分:2)
这不是一个糟糕的开始。我对它需要的分析:
对于每个生物体,高度比最大高度多一个 它吃的有机体。海藻和浮游植物为0,因为它们不适合 吃任何东西。浮游动物和帽贝是1,因为他们只吃 0级生物。
因此,从生物体到他们吃的食物清单的映射开始。您 有这个,除了你需要添加一行也将捕获 不吃任何东西的最低级生物:
with open('AquaticFoodWeb.txt') as input:
for line in input:
animal, prey = line.strip().split(' eats ')
foodweb.setdefault(animal, []).append(prey)
foodweb.setdefault(prey, []) # new line of code
其余的,只是一个大纲,因为这听起来像家庭作业和我 不会剥夺你的教育。
下一步是将foodweb
转换为来自有机体的另一个映射
到高处。在这里,我将按值的长度排序,将级别设为0
有机体在顶部,然后进行一次或多次通过。对于每个键,如果
所有猎物生物的高度都是已知的,将关键指定为最大值
高度加1,然后从foodweb
中删除此密钥。
立即添加0级生物,因为它们没有猎物。然后
我们抓住了吃它们的东西。它可能需要不止一个
传递,但最终foodweb
将为空,输出将为
满。
答案 1 :(得分:1)
我希望这不是作业,下面的代码可以解决你的问题。
animals=[]
preys=[]
with open('AquaticFoodWeb.txt','r') as f:
for line in f:
animals.append(line.split()[0])
preys.append(line.split()[-1])
height = {}
length = len(preys)
rank = 0
while preys != [None]*length:
for index,(animal,prey) in enumerate(zip(animals,preys)):
if prey not in animals:
try:
if height[prey] < rank:
height[prey] = rank
except KeyError:
height[prey] = 0
height[animal] = height[prey] + 1
preys[index] = None
animals[index] = None
rank += 1
print sorted(height.items(),key = lambda x:x[1],reverse=True)
输出:
[('Lobster', 4), ('Bird', 4), ('Fish', 3), ('Whelk', 3), ('Crab', 3),('Mussels', 2),
('Prawn', 2), ('Zooplankton', 1), ('Limpets', 1),('Phytoplankton', 0), ('Seaweed', 0)]