Python列表:如何在列表中搜索其他元素或重复项目

时间:2013-03-04 15:56:36

标签: python

我有一个列表说p = [1,2,3,4,2] 有没有任何方法可以返回bool值True如果它只包含一个副本,只使用find,indexing,切片,len()等方法而不是dict,tuple等。

我使用了这段代码:

for e in p: 
   duplicate = p.find(e, e+1) 
   if duplicate in p: 
       return True

6 个答案:

答案 0 :(得分:6)

这是一种简单的方法:

return len(p) != len(set(p))

不使用set的效率较低的方式:

for i in range(len(p)):
   if p[i] in p[i+1:]:
      return True
return False

第二种方法并不是非常惯用,但避免使用语言的所有基本功能(包括元组)。

这是另一种方式:

while p:
   e = p.pop()
   if e in p:
      return True
return False

这很简单,但会修改列表。

我要演示的最后一种方式是:

s = sorted(p)
for i in range(1, len(s)):
   if s[i] == s[i - 1]:
      return True
return False

这可以通过排序p然后比较每对连续元素来实现。

答案 1 :(得分:5)

您也可以使用list.count

def has_duplicates(p):
    for e in p:
        if p.count(e) > 1:
            return True
    return False

答案 2 :(得分:2)

>>> p = [1, 2, 3, 4, 2]
>>> len(set(p)) == len(p)
False

您可以在more information about sets中找到Python Documentation

答案 3 :(得分:1)

如果你必须这样做,你可以这样做:

def has_duplicates(lst):
    for i, e in enumerate(lst[::-1]):
        if lst.index(e) != len(lst) - i - 1:
            return True
    return False

这以相反的顺序遍历列表(因为index从列表的开头搜索)。但这样做更好:

def has_duplicates(lst):
    return len(set(lst)) != len(lst)

答案 4 :(得分:1)

使用collections.Counter

>>> import collections
>>> p
[1, 2, 3, 4, 2]
>>> if collections.Counter(p).most_common()[0][1] > 1: 
...     print('duplicate found')
... 
duplicate found
>>> if collections.Counter(set(p)).most_common()[0][1] > 1: 
...     print('duplicate found')
... 
>>> 

答案 5 :(得分:0)

这是一种非常简单的方法。对于非常大的列表,它可能会很慢。

def has_duplicates(lst):
    for e in lst:
        lst = lst[1:]
        if e in lst: return True
    return False