简体   繁体   English

如何检查列表是否已在Python中包含元素?

[英]How to check if a list already contains an element in Python?

i have been working on this for quite a time and my if statement does not seem to have any effect on the code. 我已经为此工作了很长时间,而我的if语句似乎对代码没有任何影响。 what I am trying to do is that I want to enter words in a list without repetition. 我想做的是我想在列表中输入单词而不重复。

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line.rstrip()
    words = line.split()
    if lst.count(words) == 0:
        lst = lst + words
    lst.sort()
print lst

Use a set() , it ensures unique elements. 使用set() ,可以确保元素唯一。 Alternatively, you can use the in operator to check for membership in a list ( albeit an order of magnitude less efficient ). 或者,您可以使用in运算符检查列表中的成员资格( 尽管效率低一个数量级 )。

>>> instuff = """one two three
... two three four
... three four five
... """
>>> lst = set()
>>> for line in instuff.split("\n"):
...   lst |= set(line.split())
... 
>>> lst
set(['four', 'five', 'two', 'three', 'one'])
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM