[英]How to loop over three variables in python while their sum is always equal to 1?
[英]Python: How to track two or more equal variables in a while loop
我正在嘗試計算.txt文件行中名字后面的名字數量,以便使用python使用以下代碼確定誰名字最多。
lines=0
wordCount=0
mostWordsInLine = 0
follows = open("follows.txt", "r")
for word in follows:
lines += 1
f1=word.split()
wordCount=wordCount+len(f1)
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
mostWordsInLine = word[: word.find(' ')]
print ("Most social user: " + str(mostWordsInLine))
.txt文件如下所示:
andrew fred
fred
judy andrew fred
george judy andrew
john george
我得到的輸出是:
Most social user: andrew
我的問題是我的代碼應返回judy和george,但出於某種原因返回ANDrew。 我怎樣才能解決這個問題?
wordCount=0
mostWordsInLine = 0
follows = open("follows.txt", "r")
mostFollows = []
for word in follows:
f1=word.split()
wordCount += len(f1)
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
mostFollows = [f1[0]]
elif len(f1) == mostWordsInLine:
mostFollows.append(f1[0])
print ("Most social user: " + ''.join(mostFollows))
不是直接給出家庭作業的答案,而是可以用來解決此問題以及將來可能遇到的問題的技術:在代碼中添加print
語句以了解正在發生的情況。 例如,如果我們在下面添加2條打印語句:
for word in follows:
lines += 1
f1=word.split()
wordCount=wordCount+len(f1)
print("f1 = {}, mostWordsInLine = {}".format(f1, mostWordsInLine))
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
mostWordsInLine = word[: word.find(' ')]
print(" after comparison: mostWordsInLine = {}".format(mostWordsInLine))
它將輸出以下輸出:
f1 = ['andrew', 'fred'], mostWordsInLine = 0
after comparison: mostWordsInLine = andrew
f1 = ['fred'], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
f1 = ['judy', 'andrew', 'fred'], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
f1 = ['george', 'judy', 'andrew'], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
f1 = ['john', 'george'], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
f1 = [], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
Most social user: andrew
第一次,其中一條輸出線沒有意義,請查看是否可以找出原因。
字符串庫具有.count('name')函數。 因此,您可以對for循環中的每個元素進行計數並對其進行比較。 您需要澄清問題,因為安德魯和弗雷德發生了三次。
“說得通...。首先有一個唯一名稱[names]的列表。然后使用字典來存儲它們。{name:[list_names]然后是len(string)。編寫一個對字典進行迭代並使用檢索字典的函數說話最多的人。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.