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)
还有一种方法是使用集合:
但上面的一个不是有效的。因此,为了使其有效使用,请按照falsetru在答案中的指示设置:
使用^{} operator :
您还可以使用
lis.index
,它将返回元素的索引。如果找不到元素,它将引发
ValueError
:更新
正如Nick T所评论的,如果您不关心项目的顺序,可以使用^{} :
相关问题 更多 >
编程相关推荐