我必须编写一个代码,列出所有以“the”开头的单词(例如,在那里,那么,the)。但列表中没有任何重复项。有人能帮忙吗?到目前为止,我所拥有的一切。在
def getbook():
bookname = input("What is the name of the text file?")
bookFile = open(bookname, 'r')
bookString = bookFile.read()
lowerBook = bookString.lower()
wordList = lowerBook.split()
return wordList
import string
def listAllThe(longString):
theList = []
for i in longString:
if i == 'the':
theList.append( i)
return theList
def final():
book = getbook()
getList = listAllThe(book)
print (getList)
final()
您应该签出^{} 数据类型,它不允许重复,并且在其中搜索是O(1)(恒定时间)。在
另外,您应该签出^{} 函数,如果字符串以作为参数传入的值开始,它将返回true。在
然后在}初始化为
listAllThe
函数中,可以使用函数set()
将{set
,然后进行if条件检查,如-i.startswith('the')
。在更改后的代码看起来像-
这是一种使用Python列表理解可以轻松完成的事情。生成的列表可用于初始化
set
,这将删除重复项:相关问题 更多 >
编程相关推荐