如何在Python中查找列表中的重复值

3

我想知道如何确定用户输入的值是否已经存在于列表中。

例如:

lis = ['foo', 'boo', 'hoo']

用户输入:

'boo'

现在我的问题是如何告诉用户该值已存在于列表中。

1
你的问题更多地是避免列表中的重复项。如果您不关心顺序,您也可以使用set,如果尝试添加重复项,则会忽略它。 - Nick T
哦,是的...set函数...我对它的使用有点不熟悉...但我确实见过它的运作。 - Andre
1
它不是一个函数,而是一个完整的数据类型(与 intdictliststr 一起),请参阅:https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset。 - Nick T
哦,哇...所以它比我预期的要更多!感谢NickT提供的出色信息! - Andre
2个回答

4

使用in运算符

>>> lis = ['foo', 'boo', 'hoo']
>>> 'boo' in lis
True
>>> 'zoo' in lis
False

你也可以使用 lis.index 来返回元素的索引。
>>> lis.index('boo')
1

如果找不到该元素,将会引发ValueError异常:
>>> lis.index('zoo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'zoo' is not in list

更新

正如Nick T所评论的,如果你不关心项目的顺序,可以使用set

>>> lis = {'foo', 'boo', 'hoo'}  # set literal  == set(['foo', 'boo', 'hoo'])
>>> lis.add('foo')  # duplicated item is not added.
>>> lis
{'boo', 'hoo', 'foo'}

非常感谢朋友!这帮了很多忙,也澄清了一些想法。 :) - Andre

4

另一种方法是使用集合:

import collections
lis = ['foo', 'boo', 'hoo']
# Now if user inputs boo
lis.append('boo')
print [x for x, y in collections.Counter(lis).items() if y > 1]
# Now it will print the duplicate value in output:-
boo

但是上面的方法并不高效。因此,为了使它更加高效,在答案中使用set作为falsetru的指示:
totalList= set()
uniq = []
for x in lis:
    if x not in totalList:
        uniq.append(x)
        totalList.add(x)

谢谢Hussain兄弟,这是一个非常好的例子。第二个例子简短而简洁,真的很棒。 - Andre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接