我們需要從名為 Initial_inventory-1.txt 的同一個文本檔案制作兩個字典,一個是價格,另一個是數量。兩個字典都將產品名稱作為字典中的關鍵字。
我的輸出給出了一個字典,里面有名字、價格,然后是名字的第一個字母,我不知道為什么。兩種詞典都會發生這種情況。
def read_file(file_name, prices, quantities):
file = open(file_name, 'r')
for line in file:
product = line.strip('\n').split(';')
name, price = product[0], product[1]
prices[name] = price
for price in product[0]:
prices.setdefault(price, []).append(name)
name, quantity = product[0], product[2]
quantities[name] = quantity
for quantity in product[0]:
quantities.setdefault(quantity, []).append(name)
print(prices)
print(quantities)
主功能:
def main():
#init dictionaries
prices = {}
quantities = {}
#read_file
read_file("initial_inventory-1.txt", prices, quantities)
main()
分配還有更多內容,這就是為什么它們在這些函式中的原因,我無法擺脫它們。先感謝您!
uj5u.com熱心網友回復:
product[0]是產品名稱,它是一個字串。當您迭代它時,您就是在迭代名稱中的字符。
prices和quantities字典的鍵應該是name. 您應該將其用作setdefault(). 您不應該首先分配給字典,即用此價格和數量替換價格和數量串列。
def read_file(file_name, prices, quantities):
file = open(file_name, 'r')
for line in file:
name, price, quantity = line.strip('\n').split(';')
prices.setdefault(name, []).append(price)
quantities.setdefault(name, []).append(quantity)
print(prices)
print(quantities)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346103.html
上一篇:在回圈中向資料框添加行
