【问题标题】:Python 3 - I can't print my sorted list using the .strip() function successfullyPython 3 - 我无法成功使用 .strip() 函数打印排序列表
【发布时间】:2015-03-08 02:22:40
【问题描述】:

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

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

【问题讨论】:

    标签: python list sorting printing


    【解决方案1】:

    您的函数letterSort 返回一个列表。您不能在列表中使用strip

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

    for sorted_word in letterSort(wordlist):
        print sorted_word
    

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

    【讨论】:

    • 有效!感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多