Python:如何在while循环中跟踪两个或多个相等的变量

2024-10-02 00:40:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python计算.txt文件中一行中紧跟在名字后面的名字的数量,以确定谁的名字后面最多,代码如下:

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。我怎样才能解决这个问题?你知道吗


Tags: 文件代码txtlenfred名字wordcountword
3条回答

字符串库有一个.count('name')函数。因此,您可以计算for循环中的每个元素,并对它们进行比较。你需要澄清这个问题,因为安德鲁和弗雷德出现过三次。你知道吗

“有道理……首先要有一个唯一名字的列表。然后用字典来储存它们。{name:[list\u names]然后是len(字符串)。编写一个函数,迭代字典并检索说话人最多的字典。”

不是直接回答家庭作业,而是一种可以用来解决这个问题和将来可能遇到的问题的技巧:在代码中添加print语句来理解正在发生的事情。例如,如果我们添加下面的两个print语句:

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

如果第一次某个输出行没有意义,请查看是否可以找出原因。你知道吗

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))

相关问题 更多 >

    热门问题