如何查找和计算重复次数?

2024-06-16 10:17:14 发布

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

我试着编写一个代码,让你输入五个班级,其中有五个学生,然后输出结果会告诉你谁被重复,重复了多少次

输入:

约翰尼,莉莉,约翰尼,兰登,Miii

Wii,Random,Johnny,Lily,嗯

杰伊,约翰尼,兰登,Wii,呃

强尼,强尼,强尼,强尼,强尼

嗨,再见,例如,约翰尼

例如,例二,例三,例二,例三

输出:

约翰尼:10

莉莉:2

随机:3

Wii:2

谢谢:)

print('Each class has five students.')
a=input('Enter the first class students. ')
b=input('Enter the second class students. ')
c=input('Enter the third class students. ')
d=input('Enter the fourth class students. ')
e=input('Enter the fith class students. ')

Tags: the代码inputrandom学生classeachprint
3条回答

我建议创建一个函数来处理这个问题

 # Data
class_1 = ['Johnny', 'Lily', 'Johnny', 'Random', 'Miii']
class_2 = ['Wii', 'Random', 'Johnny', 'Lily', 'Umm']
class_3 = ['Jay', 'Johnny', 'Random', 'Wii', 'Err']
class_4 = ['Johnny', 'Johnny', 'Johnny', 'Johnny', 'Johnny']
class_5 = ['???', 'Hi', 'Bye', 'Example', 'Johnny']

函数(它可以处理多个列表)

from collections import Counter

def count_names(*args, **kwargs):
    mylist = [name for name_list in args for name in name_list]
    return Counter(mylist)

结果:

count_names(class_1, class_2, class_3, class_4, class_5)

Counter({'Johnny': 10,
         'Lily': 2,
         'Random': 3,
         'Miii': 1,
         'Wii': 2,
         'Umm': 1,
         'Jay': 1,
         'Err': 1,
         '???': 1,
         'Hi': 1,
         'Bye': 1,
         'Example': 1})

这里有一个不使用计数器的替代解决方案

count = dict()

#repeat for 5 classes
for i in range(0, 5):
    students = input().split(", ")

    #add student to count
    for s in students:
        if s in count:
            count[s] += 1
        else:
            count[s] = 1

for student, occurrences in count.items():

    #print if more than one occurence
    if occurrences >= 2:
        print(student + ":" + str(occurrences))

下面是如何使用Counter()

from collections import Counter
count = Counter(a + b + c + d + e) # Add all lists together, and then count them

注意:您必须首先将输入转换为列表。下面是如何做到这一点的(根据您的输入-您可以将", "更改为您想要的任何内容):

print('Each class has five students.')
a=input('Enter the first class students. ').split(", ")
b=input('Enter the second class students. ').split(", ")
c=input('Enter the third class students. ').split(", ")
d=input('Enter the fourth class students. ').split(", ")
e=input('Enter the fith class students. ').split(", ")

相关问题 更多 >