如何在list Python中查找重复值

2024-09-30 16:31:56 发布

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

我想知道当用户输入一个值时,该值是否已经存在于列表中。

例如

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

用户输入:

'boo'

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


Tags: 用户列表fooboolishoo
2条回答

还有一种方法是使用集合:

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

但上面的一个不是有效的。因此,为了使其有效使用,请按照falsetru在答案中的指示设置:

totalList= set()
uniq = []
for x in lis:
    if x not in totalList:
        uniq.append(x)
        totalList.add(x)

使用^{} operator

>>> 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所评论的,如果您不关心项目的顺序,可以使用^{}

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

相关问题 更多 >