[英]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
>>> 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.