我试图为大多数灵活的食客编写代码,因为这种食物会吞噬食物链中最多的其他有机体,这恰好是鸟类
到目前为止,我编写的代码是:
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)))
print (" ")
#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)
print (" ")
#Producers
producers = []
allpreys = [item.strip() for sub in foodweb.values() for item in sub]
for p in allpreys:
if p.strip() not in foodweb.keys() and p not in producers:
producers.append(p)
print("The Producers Are:")
print(formatList(producers))
所以我已经编写了隔离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
输出应该说:
最灵活的食客:鸟
任何提示都将非常感谢
答案 0 :(得分:1)
您可以直接从现有的foodweb
字典计算此值,如下所示:
print("Most Flexible Eaters: {}".format(sorted(foodweb.items(), key=lambda x: -len(x[1]))[0][0]))
这会显示:
Most Flexible Eaters: Bird
这是通过按字段值的长度对字典项进行排序并选择列表中的第一项来实现的。
为了避免使用lambda
,可以写成如下:
def get_length(x):
return -len(x[1])
print("Most Flexible Eaters: {}".format(sorted(foodweb.items(), key=get_length)[0][0]))
注意,在返回的长度中添加-
只是反转排序顺序的一种技巧,或者reverse=True
可以作为参数添加到排序中以产生相同的效果。