有没有一种方法可以将值浮动到列表中然后对其进行排序?

时间:2019-08-11 03:10:12

标签: python python-3.x

要求: 您的程序应提供一个菜单驱动的界面,用户可以在其中执行以下操作:

  1. 选择退出
  2. 选择从最高到最低显示分数。
  3. 选择将分数添加到列表。注意分数必须是浮动的 点号。
  4. 选择显示最高和最低分数。

我绝对是编码方面的新手,但对操作却迷失了。

menu = """
1: Exit
2: List scores so far
3: Add a score
4: Display the highest and lowest scores
"""    


list1 = ['85.3','85.2','21.99']

done = False
while not done:

    print()
    print()
    print("Scoring Engine")
    print()
    print(menu)
    selection = input("Please enter a selection between 1 and 4: ")
    print()


    if selection == "1": #exit
        done = True

    elif selection == "2": #list scores so far
        list1 = [float(i) for i in list1]
        list1.sort(reverse=True)
        print("Scores recorded so far: ")
        print()
        print(*list1, sep="\n")

    elif selection == "3": #adds a score
        print()
        new_score = input("Please enter a score between 0 and 100: ")
        try:
            new_score = float(new_score)
        except ValueError:
            print()
            print("Please enter a valid score between 0 and 100.")
            continue
        if float(new_score)<0:
            print()
            print("{:.2f} is too low. Scores must be between 0 and 100".format(new_score))
        elif float(new_score)>100:
            print()
            print("{:.2f} is too high. Scores must be between 0 and 100".format(new_score))
        else:
            list1.append(new_score)
            print("Score added")

问题: 当我添加一个分数然后回到选项2时,我得到:

Traceback (most recent call last):
  File "C:\Users\******\Desktop\hwk4.py", line 36, in <module>
list1.sort(reverse=True)
TypeError: '<' not supported between instances of 'str' and 'float'

选择选项2时是否有办法对附加值进行排序?

1 个答案:

答案 0 :(得分:0)

按照写法,行[float(i) for i in list1]创建一个浮点数列表并将其丢弃。您只需要添加list1 =就可以拥有list1 = [float(i) for i in list1]

或者,您可以首先将列表定义为浮点数:list1 = [85.3, 85.2, 21.99]

您还应该将现有代码放入一个循环(也许是while循环)中,以便在服从用户的选择之后,它应该返回菜单并让用户做出另一个选择。 / p>