Python:比较更多数字

2024-04-20 14:24:15 发布

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

我想搜索现有列表中的号码。如果其中一个数字重复,则将变量的值设置为true并中断循环。在

list = [3, 5, 3] //numbers in list

因此,如果函数得到两个相同的数字,那么就中断-在这个例子中,有3个重复。在

怎么做?在


Tags: 函数intrue列表数字list例子号码
3条回答

你可以看看sets。您可以循环查看列表,并将该编号添加到支持集,或者中断循环。在

>>> l = [3, 5, 3]
>>> s = set()
>>> s
set([])
>>> for x in l:
...     if x not in s:
...         s.add(x)
...     else:
...         break

您还可以进一步利用这段代码生成一个函数,返回找到的第一个重复的数字(或者None,如果列表不包含重复项):

^{pr2}$

否则,如果您想得到“此列表是否包含重复项?”问题的布尔答案,可以返回它而不是重复的元素:

def has_duplicates(l):
    s = set()
    for x in l:
        if x not in s:
            s.add(x)
        else:
            return true
    return false

get_first_duplicate([3, 5, 3])
# returns True

senderle指出:

there's an idiom that people sometimes use to compress this logic into a couple of lines. I don't necessarily recommend it, but it's worth knowing:

s = set(); has_dupe = any(x in s or s.add(x) for x in l)

您可以使用collections.Counter()any()

>>> lis=[3,5,3]
>>> c=Counter(lis)
>>> any(x>1 for x in c.values()) # True means yes some value is repeated
True
>>> lis=range(10)
>>> c=Counter(lis)
>>> any(x>1 for x in c.values()) # False means all values only appeared once
False

或者使用sets并匹配长度:

^{pr2}$

首先,不要将列表命名为list。这是一个Python built-in,使用它作为变量名会产生不希望的副作用。我们改称它为L。在

通过将列表与自身的set版本进行比较,可以解决问题。在

编辑:当重复时,您需要true,而不是相反。代码已编辑。在

def testlist(L):
    return sorted(set(L)) != sorted(L)

相关问题 更多 >