Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使代码在text.split之后不打印两次单词_Python - Fatal编程技术网

Python 如何使代码在text.split之后不打印两次单词

Python 如何使代码在text.split之后不打印两次单词,python,Python,我可以添加什么使此代码不打印“sam”(在本例中)两次?尝试以下操作: text = """ sam may sam gray bet four vet large """ find = "a" words = text.split("\n") for w in words: if find in w: print(w) else : pass 使用集合

我可以添加什么使此代码不打印“sam”(在本例中)两次?

尝试以下操作:

text = """ sam 
may 
sam 
gray 
bet 
four 
vet 
large """

find = "a"

words = text.split("\n")
for w in words:
  if find in w:
    print(w)
  else :
    pass

使用集合,即
words=set(text.split(“\n”)
。缺点是,
set
s没有排序。我是否使用它而不是
words=text.split(“\n”)
这是否回答了您的问题?这是一种保持
文本的原始顺序的好方法,但它效率很低,因为在使用集合is
O(1)
时,在列表中进行查找是
O(n)
。通过将
used
定义为一个集合,您可以免费获得性能提升。
text = """
sam 
may 
sam 
gray 
bet 
four 
vet 
large """

find = "a"
used = []

words = text.split("\n")
for w in words:
  if find in w and w not in used:
    print(w)
    used.append(w)
  else :
    pass