下面的代码不像我预期的那样工作,而是反转了输入。

2024-06-26 13:25:41 发布

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

这是一个程序,它应该打印一个长度递减的字符串。但是这段代码正在反向打印给定的字符串。你知道我在这段代码中遗漏了什么吗?你知道吗

def listsorter(lst):
    lst=lst.split(" ")

    lstsize=list("a"*len(lst))
    lstindex=lstsize
    looper=len(lst)
    other=lst

    for i in range(looper):
        lstsize[i]=len(lst[i])
        lstindex[i]=lst.index(lst[i])

    while len(lstsize)>1:
        temp=max(lstsize)
        temp1=lstsize.index(temp)
        print(other[temp1])
        lstsize.pop(temp1)
    else:
        print(lst[0])

user_input=input("Enter anything\n")
listsorter(user_input)

Tags: 字符串代码inputindexlentempotherprint
2条回答

你想要这样的东西吗:

def length_sorter(s):
    words = s.split(' ')
    for w in sorted(words, key=len, reverse=True):
        print(w)

lenth_sorter('hello world i am a computer')
# prints:
computer
hello
world
am
I
a

要做到这一点而不使用内置的sorted函数,您可以构建自己的排序算法。气泡排序是最容易理解的。你知道吗

def bubble_sort(a):
    a = list(a) # make sure we are using mutable objects
    keep_sorting = True
    while keep_sorting:
        keep_sorting = False
        for i in range(len(a)-1):
            if len(a[i]) < len(a[i+1]):
                a[i+1], a[i] = a[i], a[i+1]
                keep_sorting = True
    return a

def word_sorter(s):
    words = s.split(' ')
    for w in bubble_sort(words):
        print(w)

word_sorter('hello world i am a computer')
# prints:
computer
hello
world
am
I
a

编辑:我猜詹姆斯写的是你想要的?你知道吗

相关问题 更多 >