找出列表中的重复元素。

huangapple go评论72阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2023年5月8日 00:57:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定