使用包含以下内容的虚拟文件(followst.txt
):
andrew fred
fred
judy andrew fred
george judy andrew
john george
每行的第一个名称代表用户,而后面的任何名称代表他们关注的用户。我需要能够计算每个人跟随的人数,然后返回最高数字。在这种情况下,它将返回:
george
judy
但是,我无法弄清楚如何分别计算每一行。我目前正在这样做:
fhand=open('followst.txt', 'r')
inp=fhand.read()
str= inp
words= str.split()
number_of_words=len(words)
print(number_of_words-1)
非常感谢任何帮助。
答案 0 :(得分:1)
试试这个
with open('followst.txt') as afile:
lines = afile.readlines()
follow_dict = {}
max_follower = 0
for line in lines:
names = line.split()
follow_dict[names[0]] = len(names)-1
if max_follower < len(names)-1:
max_follower = len(names)-1
for name,num_of_follower in follow_dict.items():
if num_of_follower == max_follower:
print(name)
答案 1 :(得分:0)
使用readlines
fhand=open('Test.txt', 'r')
inp=fhand.readlines()
words= [str1.split() for str1 in inp]
number_of_words=[len(word)-1 for word in words]
print(number_of_words)
m = max(number_of_words)
ids = [i for i, j in enumerate(number_of_words) if j == m]
print([word[0] for word in [words[i] for i in ids]])
这将返回
[1,0,2,2,1]
[&#39; judy&#39;,&#39; george&#39;]