gpt4 book ai didi

python - 从txt文件Python创建字典

转载 作者:行者123 更新时间:2023-11-30 23:03:38 25 4
gpt4 key购买 nike

我正在尝试获取一个包含列表的文本文件,获取输入值并以适当的输出格式对它们进行排序,但是我在尝试创建循环和创建此字典时遇到困难。

我创建了一个空白字典,但是我不确定是否应该创建一个字典以获取输出:

foodweb =
{
“Bird”: [
Prawn,
Mussels,
Crab,
Limpets,
Whelk
],
“Crab”: [
Mussels,
Limpets
],
“Fish”: [
Prawn
],
“Limpets”: [
Seaweed
],
“Lobster”: [
Crab,
Mussels,
Limpets,
Whelk
],
“Mussels”: [
Phytoplankton,
Zooplankton
],
“Prawn”: [
Zooplankton
],
“Whelk”: [
Limpets,
Mussels
],
“Zooplankton”: [
Phytoplankton
]
}

我怎样才能编写一个循环来使其更简单?!?

file_content = open('AquaticFoodWeb.txt' , 'r')
aquaticfoodweb ={}
for line in file_content:
myList=line.rstrip('\n').split(" eats ")

这是 txt 文件中的列表

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

这是我想要的输出格式:

Predators and Prey:
Bird eats Prawn, Mussels, Crab, Limpets and Whelk
Crab eats Mussels and Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab, Mussels, Limpets and Whelk
Mussels eats Phytoplankton and Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets and Mussels
Zooplankton eats Phytoplankton

最佳答案

希望以下内容对您有所帮助。您需要从一本空字典开始。对于输入的每一行,您都正确地将输入的两部分分开。然后您可以使用它们来创建字典条目。字典中的每个条目都是一个列表。 setdefault 用于允许您在发现新动物时创建一个空列表,然后自动将猎物附加到该列表中。

最后,输出需要一些思考,以确保具有多个猎物的项目已将 添加到输出中。由于字典没有排序,因此您需要在显示结果之前对其进行排序:

foodweb = {}

with open('AquaticFoodWeb.txt') as f_input:
for line in f_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))

这将为您提供以下输出:

Predators and Prey:
Bird eats Prawn, Mussels, Crab, Limpets and Whelk
Crab eats Mussels and Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab, Mussels, Limpets and Whelk
Mussels eats Phytoplankton and Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets and Mussels
Zooplankton eats Phytoplankton

关于python - 从txt文件Python创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34018683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com