通过数据排序

这类似于我正在学习编写代码的书中的示例。我有一个函数,希望根据“ for”构造的参数对输入数据进行排序,但不会对数据进行排序。我究竟做错了什么?我正在学习,要变得温柔! :)

def sort_high_to_low(user_prompt="Please enter the amount of stands you want to enter sales for: "):
    user_input = int(input(user_prompt))

    for count in range(1,user_input + 1):
        prompt = "Please enter the sales for stand " + str(count) + ": "
        sales.append(read_int(prompt))


    print(sales)


    for sort_pass in range(0,len(sales)):
        for count1 in range(0,len(sales)-1):
            if sales[count1] < sales[count1 + 1]:
                temp = sales[count1]
                sales[count1] = sales[count1+1]
                sales[count1+1] = temp

sort_high_to_low()
a53932991 回答:通过数据排序

您需要先将sales初始化为函数开头的空列表,然后将return sales初始化为函数的空列表,或者将sales全局初始化为空列表。

sales = []

为什么不使用sales.sort()代替嵌套的for循环排序算法?

有人评论read_int无效,请使用

int(i) for i in input(prompt).split()

相反,如果您想在一行上输入多个条目

,

以下代码有效:

def sort_high_to_low(user_prompt="Please enter the amount of stands you want to enter sales for: "):
    user_input = int(input(user_prompt))
    print(user_input)
    sales = []
    for count in range(1,user_input + 1):
        prompt = "Please enter the sales for stand " + str(count) + ": "
        sales.append(int(input(prompt)))

    print(sales)
    print(sorted(sales))
sort_high_to_low()
本文链接:https://www.f2er.com/3129514.html

大家都在问