英文:
Find recurring element from list
问题
Here is the translated code portion:
list=['A', 'R', 'I','J','I','T','T']
def reccuring():
count=0
list1=[]
for i in list:
if list.count(i)>1:
list1.append(i)
return list1
reccuring()
And the translated output:
['I', 'I', 'T', 'T']
我得到了重复的元素,重复的次数与列表中的出现次数一样多。我需要做哪些修改才能只获取重复的元素一次?
谢谢
英文:
list=['A', 'R', 'I','J','I','T','T']
def reccuring():
count=0
list1=[]
for i in list:
if list.count(i)>1:
list1.append(i)
return list1
reccuring()
OutPut
['I', 'I', 'T', 'T']
I am getting the recurring elements as many times as present in the list. What modification do I have to do to get the recurring elements only once?
Thank You
答案1
得分: 0
请更好地命名您的变量并使用set
values = ['A', 'R', 'I', 'J', 'I', 'T', 'T']
def recurring():
count = 0
result = set()
for value in values:
if value not in result and values.count(value) > 1:
result.add(value)
return result
recurring()
英文:
Better name your variables and use a set
values = ['A', 'R', 'I', 'J', 'I', 'T', 'T']
def reccuring():
count = 0
result = set()
for value in values:
if value not in result and values.count(value) > 1:
result.add(value)
return result
reccuring()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论