我想知道如何确定用户输入的值是否已经存在于列表中。
例如:
lis = ['foo', 'boo', 'hoo']
用户输入:
'boo'
现在我的问题是如何告诉用户该值已存在于列表中。
我想知道如何确定用户输入的值是否已经存在于列表中。
例如:
lis = ['foo', 'boo', 'hoo']
用户输入:
'boo'
使用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'}
另一种方法是使用集合:
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
totalList= set()
uniq = []
for x in lis:
if x not in totalList:
uniq.append(x)
totalList.add(x)
set
,如果尝试添加重复项,则会忽略它。 - Nick Tint
、dict
、list
和str
一起),请参阅:https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset。 - Nick T