[英]Creating a dictionary with nested list with reader + itertools (reading from txt file)
I have created this file and want the return-parameter be a dictionary with the form {animal name: [date, weight]...}我已经创建了这个文件,并希望返回参数是一个格式为 {animal name: [date, weight]...} 的字典
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)
I read from a file with the following format:我从具有以下格式的文件中读取:
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
But all I get is an empty dictionary when doing print(readanimal("filename.txt")).但是在执行 print(readanimal("filename.txt")) 时,我得到的只是一个空字典。 What have I done wrong?
我做错了什么?
I don't think groupby
adds a lot of value here;我不认为
groupby
在这里增加了很多价值。 it's easier to just keep track of which animal you're on as you add each row to the dictionary.当您将每一行添加到字典中时,跟踪您所使用的动物会更容易。 (It would be a lot easier of the type of animal was a column instead of a header row -- then you could indeed
groupby
that value and this would practically be a one-liner.) (动物的类型是一列而不是
groupby
行会容易得多——那么你确实可以按该值分组,这实际上是一个单行。)
Simplified input file animals.txt
(since yours wasn't valid as-is):简化的输入文件
animals.txt
(因为你的不是有效的):
Pig
21-10-26 96.58
21-10-27 95.35
Bear
21-10-22 100
21-10-25 100
and code that just builds the dict as I described:和我描述的只是构建字典的代码:
import csv
def readanimal(filename):
animal_map = {}
current = []
with open(filename, encoding="utf-8") as file:
for row in csv.reader(file, delimiter="\t"):
if len(row) == 1:
current = []
animal_map[row[0]] = current
else:
current.append(row)
return animal_map
print(readanimal("animals.txt"))
prints:印刷:
{'Pig': [['21-10-26', '96.58'], ['21-10-27', '95.35']], 'Bear': [['21-10-22', '100'], ['21-10-25', '100']]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.