我只是编程的初学者,最近我做了一个简单的调查:
survey = {}
polling_active = True
while polling_active:
name = input("To take part in the survey, enter your name: ")
anwser = input("What's your favourite computer game? ")
survey[name] = anwser
repeat = input("Is there enyone else who wants to participate in the
survey? (yes/no): ")
if repeat.lower() =="no":
polling_active = False
number_of_users = len(servey.keys())
print(str(liczba_uzytkownikow) + " took part in the survey!")
print("----------Survey results----------")
for name, anwser in survey.items():
print("\nName: " + imie)
print("\nFavourite game: " + anwser)
这并不是很复杂,但是我想做一件事。我想添加一个功能或类似的功能来检查是否重复任何答案。我该怎么办?我应该使用该功能还是什么?我希望它: 1.计算我得到了多少个答案 2.也许创建一个字典,其中包含一个答案以及该答案在答案列表中的次数 3.计算答案在字典中出现的次数。
我还发现我曾经写过“ anwser”而不是“ answer”。...
答案 0 :(得分:1)
您可以使用from collections import Counter
print([a for a, n in Counter(survey.values()).items() if n > 1])
查找不止一个数的答案:
[sudo] npm cache clean -f
[sudo] npm install -g n stable
答案 1 :(得分:1)
一种方法可以告诉您哪些答案已被多次回答:
seen_answers = set()
multiples = set()
for answer in list(survey.values()):
if answer not in seen_answers:
seen_answers.add(answer)
else:
multiples.add(answer)
# multiples contains the answers that have been said more than once
如果您只想查找已被多次回答的答案,则可以:
answers = list(survey.values())
len(set(answers)) - len(answers)