[英]Creating a dictionary with nested list with reader + itertools (reading from txt file)
我已經創建了這個文件,並希望返回參數是一個格式為 {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)
我從具有以下格式的文件中讀取:
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
但是在執行 print(readanimal("filename.txt")) 時,我得到的只是一個空字典。 我做錯了什么?
我不認為groupby
在這里增加了很多價值。 當您將每一行添加到字典中時,跟蹤您所使用的動物會更容易。 (動物的類型是一列而不是groupby
行會容易得多——那么你確實可以按該值分組,這實際上是一個單行。)
簡化的輸入文件animals.txt
(因為你的不是有效的):
Pig
21-10-26 96.58
21-10-27 95.35
Bear
21-10-22 100
21-10-25 100
和我描述的只是構建字典的代碼:
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"))
印刷:
{'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.