我已经创建了这个文件,并希望返回参数是一个字典,格式为{动物名称:日期,体重...}
import itertools
import csv
def readanimal(file):
animal_map = {}
with open(filnamn, encoding="utf-8") as file:
reader = csv.reader(file, delimiter="\t")
for new_animal, rows in itertools.groupby(reader, lambda row: len(row) == 1):
if new_animal:
animal = next(rader)[0]
else:
animal_map[animal] = list(rows)
del animal
return(animal_map)我从以下格式的文件中读取:
Pig
21-10-26 96.58
21-10-27 95.35
21-10-28 94.36
21-10-29 94.00
21-11-01 93.26
21-11-02 91.93
21-11-03 93.52
21-11-04 93.58
21-11-05 95.00
21-11-08 95.36
21-11-09 95.89
21-11-10 96.26
Bear
21-10-22\t [weight] (for every date below)
21-10-25
21-10-26
21-10-27
21-10-28
21-10-29
21-11-01
21-11-02
21-11-03
21-11-04
21-11-05但在打印时,我得到的只是一本空字典(readanimal(“filename.txt”))。我做错了什么?
发布于 2021-11-22 19:52:31
我不认为groupby在这里增加了太多价值;当您将每一行添加到字典中时,只跟踪您所在的动物会更容易一些。(动物的类型是列而不是标题行要容易得多--这样您就可以groupby该值,这实际上是一行代码。)就这一点而言,与只使用split相比,csv并没有增加太多价值。
简化的输入文件animals.txt (因为您的输入文件按原样无效):
Pig
21-10-26 96.58
21-10-27 95.35
Bear
21-10-22 100
21-10-25 100以及像我描述的那样构建字典的代码:
def readanimal(filename):
animal_map = {}
current = []
with open(filename) as file:
for row in map(str.split, file):
if len(row) == 1:
current = []
animal_map[row[0]] = current
else:
current.append(row)
return animal_map
print(readanimal("animals.txt"))打印:
{'Pig': [['21-10-26', '96.58'], ['21-10-27', '95.35']], 'Bear': [['21-10-22', '100'], ['21-10-25', '100']]}https://stackoverflow.com/questions/70071450
复制相似问题