简体   繁体   中英

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. 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. Alternatively, you can use the in operator to check for membership in a list ( albeit an order of magnitude less efficient ).

>>> 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'])
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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