Python 中包含重复项
pythonserver side programmingprogramming更新于 2025/10/31 6:04:17
假设我们有一个数字列表。我们必须检查列表中是否包含一些重复元素。因此,如果列表为 [1,5,6,2,1,3],则它将返回 1,因为有两个 1,但如果列表为 [1,2,3,4],则它将为 false,因为不存在重复项。
为了解决这个问题,我们将采用这种方法 −
我们知道集合数据结构仅包含唯一数据。但列表可以折叠重复内容。因此,如果我们将列表转换为集合,如果有任何重复元素,其大小将减小,通过匹配长度,我们可以解决这个问题。
示例
让我们看下面的实现,以便更好地理解 −
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ return not len(nums) == len(set(nums)) ob1 = Solution() print(ob1.containsDuplicate([1,5,6,2,1,3])) print(ob1.containsDuplicate([1,2,3,4]))
输入
nums = [1,5,6,2,1,3] nums = [1,2,3,4]
输出
True False
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

