Python 3 - 我无法使用 .strip() 函数成功打印我的排序列表

Python 3 - I can't print my sorted list using the .strip() function successfully

我想打印一个列表,每行一个字,但是当我打印排序后的版本时,我似乎无法做到这一点。我的文本文件只有五个字,每行一个,

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

你的函数letterSortreturns一个列表。您不能在列表中使用 strip

要在新行上打印列表的每个元素,请将 main 函数中的最后两行替换为:

for sorted_word in letterSort(wordlist):
    print sorted_word

在最后一个 for 循环中,您遍历文件中的所有单词并多次调用排序函数,而您只需要调用一次。这就是为什么你的排序列表被打印了 5 次(因为你的文件中有 5 行)