为了账号安全,请及时绑定邮箱和手机立即绑定

用户输入以降序排列输出

用户输入以降序排列输出

狐的传说 2021-10-26 17:02:54
用户输入,其中输出将按降序排序。例如,输入一个数字:你想输入更多:如果是打印输入另一个数字如果回答否打破argument并按降序对输出进行排序。我已经用于raw_input查询和使用while 循环来运行代码。但它仅按降序对第一个输出和最后一个输出进行排序a = raw_input("Enter a number: ")while True:    b = raw_input("Do you want to input more: ")    c = raw_input("Enter another number:")    if b == 'yes':        print (c)        continue    elif b == 'no':        my_list = [a,c]        my_list.sort(reverse=True)        print(my_list)        break我希望代码能够成功运行Enter a number:2Do you want to input more:yesEnter another number:3Do you want to input more:yesEnter another number:4Do you want to input more:no[4,3,2]
查看完整描述

3 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

在Python 3.x 中,使用input()代替raw_input()


创建一个list将用户输入附加到其中,以便稍后对其进行排序。


input_List = []

input_List.append(int(input("Enter a number: ")))


while True:

    b = input("Do you want to input more: ")

    if b == 'yes':

        input_List.append(int(input("Enter a number: ")))

    elif b == 'no':

        input_List.sort(reverse=True)

        break


print(input_List)

输出:


Enter a number: 5

Do you want to input more: yes

Enter a number: 7

Do you want to input more: yes

Enter a number: 90

Do you want to input more: no

[90, 7, 5]


查看完整回答
反对 回复 2021-10-26
?
LEATH

TA贡献1936条经验 获得超6个赞

它应该是这样的:


a = input("Enter a number: ")

l = [int(a)]

while True:

    b = input("Do you want to input more: ")

    if b == 'yes':

        c = input("Enter another number:")

        l.append(int(c))

    elif b == 'no':

        l.sort(reverse=True)

        print(l)

        break


查看完整回答
反对 回复 2021-10-26
?
慕仙森

TA贡献1827条经验 获得超8个赞

很多逻辑错误,还有更微妙的错误

  • raw_input 返回一个字符串,除非您转换为整数,否则您将无法获得正确的数字排序。

  • 是/否问题逻辑被打破,来得太晚了......

  • 你永远不会append在你的列表中使用,它总是包含 2 个元素。my_list = [a,c]没有意义。

我的建议:

# this is for retrocompatibility. Python 3 users will ditch raw_input altogether

try:

    raw_input

except NameError:

    raw_input = input   # for python 3 users :)


# initialize the list with the first element

my_list = [int(raw_input("Enter a number: "))]


while True:

    b = raw_input("Do you want to input more: ")

    if b == 'yes':

        # add one element

        my_list.append(int(raw_input("Enter another number:")))

    elif b == 'no':

        my_list.sort(reverse=True)

        print(my_list)

        break


查看完整回答
反对 回复 2021-10-26
  • 3 回答
  • 0 关注
  • 216 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号