我是python的新手,我現在可以真正使用你的幫助和指導。我想基於第一和第二列讀三米的cols一個CSV文件,並做一些計算即通過動態創建嵌套字典來計算聚合
A spent 100 A spent 2040
A earned 60
B earned 48
B earned 180
A spent 40
.
.
.
其中A花了2040將是除了所有「A」和「花」數額。這不會給我一個錯誤,但它不是邏輯上是正確:
for row in rows:
cols = row.split(",")
truck = cols[0]
if (truck != 'A' and truck != 'B'):
continue
record = cols[1]
if(record != "earned" and record != "spent"):
continue
amount = int(cols[2])
#print(truck+" "+record+" "+str(amount))
if truck in entries:
#entriesA[truck].update(record)
if record in records:
records[record].append(amount)
else:
records[record] = [amount]
else:
entries[truck] = records
if record in records:
records[record].append(amount)
else:
entries[truck][record] = [amount]
print(entries)
我知道,這部分不正確,因爲我會被添加相同的內部詞典列表外的字典,但我不知道如何從那裏:
entries[truck] = records
if record in records:
records[record].append(amount)
然而,林不知道的語法來動態創建一個新的字典,不會是「記錄」
我越來越:
{'B': {'earned': [60, 48], 'spent': [100]}, 'A': {'earned': [60, 48], 'spent': [100]}}
但希望能得到:
{'B': {'earned': [48]}, 'A': {'earned': [60], 'spent': [100]}}
感謝。
這個術語是*「A的總支出是2040」*。是的,熊貓包是這樣做的,強烈推薦。 – smci
更好地短語問題*「如何計算聚合?」*比詢問實現*「創建嵌套字典」*。閱讀有關拆分應用組合範例。 – smci
在你的預期結果中,你爲什麼期望B的收入是48而不是228?類似的花費,不應該是140嗎?你提到了你的問題的總和,但現在看來你只想要第一個? – chthonicdaemon