gpt4 book ai didi

python - 在字典中创建多个动态字典

转载 作者:行者123 更新时间:2023-11-28 21:37:44 24 4
gpt4 key购买 nike

我有多个文本文件。每个文件都是动物列表及其在房屋中的数量。像这样:

房子A.txt

cats 3  
dogs 1
birds 4

房子B.txt

cats 5  
dogs 3
birds 1

我有大约 20 个房子,每个房子有大约 16000 个物种(所以每个文件有大约 16000 行。所有房子都有相同的物种,只是每个物种的数量不同。

我当前的脚本逐行循环遍历每个文件,并捕获房屋、物种名称及其数量。

我想创建一个房屋字典,其中每个房屋都是动物及其数量的字典。所以从上面的例子来看,结果应该是这样的:

dictOfDicts{houseA:{'cats': 3, 'dogs': 1, 'birds': 4}, houseB:{'cats': 5, 'dogs': 3, 'birds': 1}}

如果您想知道,稍后会把它变成一个表格:

      house:   A   B
animal
cats 3 5
dogs 1 3
birds 4 1

这是我的脚本:

#!/usr/bin/python3
import sys


houseL = []
dictList = []
with open(sys.argv[1], 'r') as files:
for f in files:
f = f.rstrip()
with open(f, 'r') as aniCounts:
house = str(aniCounts).split(sep='/')[2] # this and the next line captures the house name from the file name.
house = house.split('.')[0]
houseL.append(house)

for line in aniCounts:
ani = line.split()[0]
count = line.split()[1]
#print(ani, ' ', count)

编辑:感谢一位乐于助人的评论者,将问题更改为口述的口述。

最佳答案

我会尝试这样的事情:

house_names = ['houseA', 'houseB', ...]
houses_dict = {}

for house in house_names:
houses_dict[house] = {}

with open(house + '.txt') as f:
for line in f:
species, num = line.rsplit(maxsplit=1) # split off rightmost word
houses_dict[house][species] = int(num)

结果将是(例如):

houses_dict = {
'houseA': {
'cats': 3
'dogs': 1
'birds': 4
},
'houseB': {
'cats': 5
'dogs': 3
'birds': 1
}
...
}

关于python - 在字典中创建多个动态字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49049378/

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