如何防止Python的追加方法替换现有值?

时间:2016-05-19 08:16:53

标签: python append

我正在尝试按升序和降序排序用户输入的数字,但是append方法一直在替换先前的值,因此我只在订购中得到一个数字。

print("This is a program to order numbers in ascending and descending order.")
while 1 == 1:
    until = int(input("\nEnter how many numbers you want ordered: "))
    print("")
    loop = 0
    while loop < until:
        numbers = []
        number = float(input("Enter number: "))
        numbers.append(number)
        loop += 1
    print("\nHere are the numbers in descending order:")
    while len(numbers) > 0:
        print(max(numbers))
        largest = max(numbers)
        numbers.remove(largest)

4 个答案:

答案 0 :(得分:4)

在您的代码中,您在循环中编写了以下行;

numbers = []

每次遍历循环时,您将创建一个新变量numbers,因此每次迭代都会覆盖它。

试试这个;

print("This is a program to order numbers in ascending and descending order.")
while 1 == 1:
    until = int(input("\nEnter how many numbers you want ordered: "))
    print("")
    loop = 0
    numbers = []
    while loop < until:            
        number = float(input("Enter number: "))
        numbers.append(number)
        loop += 1
        print("\nHere are the numbers in descending order:")
    while len(numbers) > 0:
        print(max(numbers))
        largest = max(numbers)
        numbers.remove(largest)

答案 1 :(得分:1)

问题是由numbers = []循环中的行while引起的。在您附加下一个数字之前,这会在每次迭代时将numbers重置为空列表。

要解决此问题,只需将此行移至while循环之外,如下所示:

loop = 0
numbers = []
while loop < until:
    number = float(input("Enter number: "))
    numbers.append(number)
    loop += 1

请注意,在此实例中,您还不需要loop变量。您可以直接测试numbers列表的长度,如下所示:

numbers = []
while len(numbers) < until:
    number = float(input("Enter number: "))
    numbers.append(number)

答案 2 :(得分:1)

您的号码是本地的

print("This is a program to order numbers in ascending and descending order.")
while 1 == 1:
    numbers = []
    until = int(input("\nEnter how many numbers you want ordered: "))
    print("")
    loop = 0
    while loop < until:
        #numbers = []
        number = float(input("Enter number: "))
        print(number, numbers)
        numbers.append(number)
        loop += 1
    print("\nHere are the numbers in descending order:")
    while len(numbers) > 0:
        print(max(numbers))
        largest = max(numbers)
        numbers.remove(largest)

答案 3 :(得分:0)

在您的初始代码中,您说明您需要按降序排列的数字,我还没有提供完整的解决方案,但是大致了解哪里可以使用您目前拥有的内容。只需要根据用户需求,降序或升序添加更多逻辑。我不知道为什么你有数字。删除(最大)所以我评论了

    numbers = []
    print("This is a program to order numbers in ascending and descending order.")
    numbers
    while True:

        until = int(input("\nEnter how many numbers you want ordered: "))
        print("")
        loop = 0
        while loop < until:

            number = float(input("Enter number: "))
            numbers.append(number)
            loop += 1
        print("\nHere are the numbers in descending order:")
        numbers.sort()
        print(numbers)
        largest = max(numbers)
        #numbers.remove(largest)

如我原来的评论中所述&#34;声明你的列表编号= []高于一个等级,你试过吗?&#34;