python - 如何制作一个程序来告诉我列表中的重复值并告诉你重复值在哪里?
问题描述
我开始学习 Python,我必须让这段代码为家庭作业工作。
这是我所做的
#Presentation
print("This program find all the repeated values in a list and they tell you in what position they are")
print("First you have to make a list for that tell me")
#Input
elements=int(input("How many items does this list have? "))#Only for int
print("Tell me the items on this list")
list=[]
repeated=[]
counter=0
while counter != elements:
a=int(input("=>"))#It only accepts integers but you have to be able to add any element
list.append(a)
counter=counter+1
#From here we already insert a list with n elements and name each element
#Now we have to see if there are repeated values
n=0
k=0
while k != elements:
for i in list:
if i == list[k]:
n=n+1
repeated.append(k)
print (list[k],"repeated",n,"times")
script=list[k]
print(list[k],"is on the position number",list.index(script))
n=0
k=k+1
我进行了研究,我知道有更简单的方法可以通过创建字典来了解元素重复的次数,但我仍然无法使用它,因为我没有在我正在学习的课程中学习
我目前唯一的问题是 - 如何让它只出现一次它重复多少次?-如何知道所有重复而不只是第一个重复在哪个位置?
这是该程序当前打印的示例
This program find all the repeated values in a list and they tell you in what position they are
First you have to make a list for that tell me
How many items does this list have? 7
Tell me the items on this list
=>3
=>5
=>4
=>5
=>5
=>2
=>3
3 repeated 2 times
3 is on the position number 0
5 repeated 3 times
5 is on the position number 1
4 repeated 1 times
4 is on the position number 2
5 repeated 3 times
5 is on the position number 1
5 repeated 3 times
5 is on the position number 1
2 repeated 1 times
2 is on the position number 5
3 repeated 2 times
3 is on the position number 0
虽然我现在学的是很基础的东西,如果你也能留下一个更优化更简单的方法来解决这个问题,即使是更高级的也很有帮助,我很好奇也因为我想学更多.
解决方案
这很可能不是最好的方法,但你说你只是想用字典完成它,所以你去吧。
#Presentation
print("This program find all the repeated values in a list and they tell you in what position they are")
print("First you have to make a list for that tell me")
#Input
elements=int(input("How many items does this list have? "))
print("Tell me the items on this list")
dicts = {}
counter=0
while counter != elements:
a=int(input("=>"))
dicts[counter] = a
counter=counter+1
rev_dict = {}
for key, value in dicts.items():
rev_dict.setdefault(value, set()).add(key)
result = filter(lambda x: len(x)>1, rev_dict.values())
for x in result:
print("At Positions " + str(x) + " The Value is " + str(dicts[next(iter(x))]))
一个很好的资源https://www.geeksforgeeks.org/python-find-keys-with-duplicate-values-in-dictionary/
推荐阅读
- r - 将列表的每个元素与R中另一个列表的元素组合
- r - ggplot2中其他美学参数的统计摘要位置
- delphi - 自定义托管记录和内存泄漏
- ios - 领域数据库 ios swift。获取列表中关键字的出现次数
- chart.js - 如何将工具提示值从大到小排序
- javascript - 如何随机化数组
- json - 创建数据库记录时如何加载预加载关联?
- go - go-swagger restapi/configure_todo_list.go - api.TodoGetHandler 未定义错误
- arrays - 使用 AWK 选择输入记录字段
- reactjs - 防止由于简单反应组件之间的替换而导致的重新渲染