[英]Trying to figure out the correct loop for processing multiple lines into a dictionary
grocery_stock.txt包含
lemonade 6 1.1 bread 34 1.43 chips 47 3.76 banans 16 0.79 pizza 15 5.0
到目前為止,這是我為此編寫的代碼。
infile=open("grocery_stock.txt", 'r+')
lines=infile.readlines()
line=infile.readline()
none= ' '
count = 0
index= 0
while line !=none:
line1=infile.readline()
while line1 in lines:
line1=line1.split()
name1=str(line1[:0])
quant1=(str(line1[:1]))
price1=[(str(line1[:2]))]
grocerystock[name1[0]]=(quant1,name1)
print (grocerystock)
line2=infile.readline()
for line2 in line:
line1=line2.split()
name1=str(line1[0])
quant1=(str(line1[1]))
price1=[(str(line1[2]))]
grocerystock[name1[1]]=(quant1,name1)
print (line1[1], line[2],line1[0])
print (grocerystock)
line3=infile.readline()
line4=infile.readline()
line5=infile.readline()
infile.close()
grocerystock={}
我這樣做的原因是因為稍后在我的項目中,我將必須刪除一些鍵並更改一些值,以便我想要一個可以在我讀取文件以將數據轉換為字典時在程序中任意調用的函數。
我的循環對您來說可能看起來很瘋狂,但是我正要嘗試嘗試突然出現的任何事情。
另外,如您所見,我還沒有完成第5行,我認為找出正確的循環而不是鍵入隨機循環並看看會發生什么會更好。
先感謝您。
也許這會有所幫助:
with file('grocery_stock.txt') as f:
lines = f.readlines()
# filter out empty lines
lines = [line for line in lines if line.strip() != '']
# split all lines
lines = [line.split() for line in lines]
# convert to a dictionary
grocerystock = dict((a, (b, c)) for a, b, c in lines)
# print
for k, v in grocerystock.items():
print k, v
您唯一需要的循環是逐行移動數據的循環。 可以這樣實現:
with open("grocery_stock.txt", "r+") as f:
for line in f: # Changed to be a more elegant solution; no need to use while here.
# Here we would split (hint) the line of text.
dict[split_text[0]] = [split_text[1], split_text[2]]
既然是家庭作業,我鼓勵您和其他人一起研究此解決方案。 我不能只給你答案,現在可以嗎?
只是一些提示,因為這是硬件:
with
語句 , while
並沒有錯,在這種情況下,我還是更喜歡使用for循環(迭代次數是固定的-行數)–我有時將while循環視為解決暫停問題的途徑 ... 嘗試使用readlines()
,因為行數可能很小; 或使用類似以下的內容(看起來很自然):
for line in f: # do something with line
當使用open()
並獲得文件對象時,可以僅在文件對象上進行迭代。 像這樣:
for line in f:
# do something with the line
我建議使用上面的方法,而不是循環調用f.readline()
。
f.readlines()
會將整個文件讀入內存,並構建輸入行列表。 對於非常大的文件,這可能會導致性能問題。 對於您在此處使用的小文件,它可以工作,但是如果您學習標准的Python習慣用法,則可以將其用於小文件或大文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.