我想打印一个每行一个单词的列表,但当我打印排序后的版本时,我似乎无法做到这一点。我的文本文件只有五个字,每行一个
dog
bit
mailman
cat
anteater
代码方面一切都很好,只是解决了如何正确打印出来。你知道吗
def letterSort(wordlist):
letterbin = [[] for _ in range(26)]
final = []
for line in open(wordlist):
word = line.strip().lower()
firstLetter = word[0]
index = ord(firstLetter) - ord('a')
bins = letterbin[index]
if not word in bins:
bins += [word]
for bins in letterbin:
insertion_sort(bins)
final += bins
return final
def swap( lst, i, j ):
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
def insert( lst, mark ):
index = mark
while index > -1 and lst[index] > lst[index+1]:
swap( lst, index, index+1 )
index = index - 1
def insertion_sort( lst ):
for mark in range( len( lst ) - 1 ):
insert( lst, mark )
def main():
wordlist = input("Enter text file name: ")
print("Input words:", )
for line in open(wordlist):
print(line.strip())
print("\n")
print("Sorted words:", )
for line in open(wordlist):
print(letterSort(wordlist.strip()))
main()
在这一切之后,我得到的是:
Enter text file name: wordlist.txt
Input words:
dog
bit
mailman
cat
anteater
Sorted words:
['anteater', 'bit', 'cat', 'dog', 'mailman']
['anteater', 'bit', 'cat', 'dog', 'mailman']
['anteater', 'bit', 'cat', 'dog', 'mailman']
['anteater', 'bit', 'cat', 'dog', 'mailman']
['anteater', 'bit', 'cat', 'dog', 'mailman']
函数
letterSort
返回一个列表。不能在列表上使用strip
。你知道吗要在新行上打印列表的每个元素,请将
main
函数中的最后两行替换为:在上一个
for
循环中,您迭代了文件中的所有单词并多次调用sort函数,而您只需要调用一次。这就是为什么排序列表会打印5次(因为文件中有5行)相关问题 更多 >
编程相关推荐