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

2024-03-29 15:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: inmailmanforindexdeflinebitcat
1条回答
网友
1楼 · 发布于 2024-03-29 15:35:21

函数letterSort返回一个列表。不能在列表上使用strip。你知道吗

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

for sorted_word in letterSort(wordlist):
    print sorted_word

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

相关问题 更多 >