在我的程式中,我正在遍歷 .txt 檔案中的行。我將這些行添加到字典中,具體取決于它們是以文本還是數值開頭。在數字行的實體之間,我想計算出現字串的行數。我還將數字行的內容和字串行數添加到字典中。
我的檔案看起來像這樣:6/10/21 string string string 6/11/21
但是,我過早退出回圈,我不知道為什么。例如,我的程式只計算兩行字串而不是三行。這是我的一些代碼:
count = 0
for i in myfile:
if i[0].isdigit():
s = i.strip()
my_dict["Numeric"].append(s)
if i[0].isdigit()==False:
count = count 1
next_ln = next(myfile)
if next_ln[0].isdigit():
print(next_ln)
my_dict["String Count"].append(count)
count = 0
在我的代碼的另一個版本中,我將最終的 if 陳述句與其他陳述句對齊,但它并沒有改變任何東西。抱歉,如果之前有人問過這個問題,或者這是一個非常明顯的問題,但我找不到任何有助于解決我的問題的東西。
uj5u.com熱心網友回復:
我假設my_dict["String Count"]是字串行數my_dict["Numeric"]串列和數字行串列。
這里的目標是避免在next()for 回圈中使用,因為這會擾亂 for 回圈的功能,從而給您帶來不希望的結果。
這是我的解決方案:
for i in myfile:
if i[0].isdigit():
s = i.strip()
my_dict["Numeric"].append(s)
# initiating a new element 0 to the count list
my_dict["String Count"].append(0)
else:
# incrementing the value of the last present number in the count list by 1
my_dict["String Count"][-1] = 1
在這里,我還假設任何不是以數字開頭的都是字串。else您可以對條款進行必要的修改,使其成為elif您想要的條件或任何其他條件。
最終結果是,其中的每個數字行都my_dict["Numeric"]將有一個對應的數字(在同一索引處),其中my_dict["String Count"]包含其后面的字串行數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495169.html
