Python按字母顺序排列3个单词

2024-04-18 15:48:15 发布

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

所以我写了一个按字母顺序排列三个单词的代码,但我很酷,实际上是按字母顺序排列的(如果两个单词都以h开头,它将转到第二个字母)。我基本上是一个初学者,所以没有什么先进的我只是使用while循环。我让代码工作过一次,但后来它停止了工作。外面的老师在方向说我们写的函数不能有返回,所以这里是我的代码。你知道吗

def printInOrder(str1, str2, str3):
    i = 0
    i = int(i)
    list_1 = [str1, str2, str3]
    while i < len(str1) < len(str2) < len(str3):
        if list_1[0][i] = list_1[1][i] = list_1[2][i]:
            i += 1 
        elif list_1[0][i] < list_1[1][i] < list_1[2][i]:
            first = list_1[0]
            second = list_1[1]
            third = list_1[2]
        elif list_1[0][i] < list_1[2][i] < list_1[1][i]:
            first = list_1[0]
            second = list_1[2]
            third = list_1[1]
        elif list_1[1][i] < list_1[0][i] < list_1[2][i]:
            first = list_1[1]
            second = list_1[0]
            third = list_1[2]
        elif list_1[1][i] < list_1[2][i] < list_1[0][i]:
            first = list_1[1]
            second = list_1[2]
            third = list_1[0]
        elif list_1[2][i] < list_1[0][i] < list_1[1][i]:
            first = list_1[2]
            second = list_1[0]
            third = list_1[1]
        else:
            first = list_1[2]
            second = list_1[1]
            third = list_1[0]


    first = str(first)
    second = str(second)
    third = str(third)
    print(first,second,third)

Tags: 代码len字母单词listfirstsecondelif
2条回答

您需要:

if list_1[0][i] == list_1[1][i] == list_1[2][i] 

as==用于比较,=用于python中的赋值。还有

i=int(i) 

不需要,因为python可以将0识别为整数。我们不需要为变量指定类型。 另一个主要错误是必须在循环结束时增加i,i=i+1。条件:

i < len(str1) < len(str2)< len(str3) 

也是错误的,因为只有当i<;len(str1)和 len(str1)<;len(str2)和len(str2)<;len(str3),不一定每次都是这样!相应地改变你的逻辑。。 下面是使用Python的简单内置函数的代码:

def printInOrder(str1, str2, str3):
    list_1 = [str1, str2, str3]
    list_1.sort()
    first = list_1[0]
    second = list_1[1]
    third = list_1[2]
    print first,second,third
printInOrder('hat','harry','ham')

在我看来,你提出的解决办法与老师的意图相矛盾。我强烈假设(s)他想让你学习排序树或决策树-所以你只需要if子句。参见sorting int array with only 3 elements了解一些解决方案和进一步阅读。你知道吗

相关问题 更多 >