简体   繁体   English

如何在while循环中接受、存储和排序值?

[英]How to accept, store and sort the values in while loop?

I want to accept input from a user and store them in the empty list and sort that values and then print it but I'm getting last value printed.我想接受来自用户的输入并将它们存储在空列表中并对这些值进行排序然后打印它,但我正在打印最后一个值。

sort_value = [].sort(key=int)
chances = 1

while chances <= 5:
    a = int(input("Enter a number"))
    if a >= 0:
        sort_value = a
        chances += 1
print(sort_value)

sort_value = [].sort() will assign None to sort_value since sort() doesn't have return statement. sort_value = [].sort()None分配给sort_value因为sort()没有return语句。

sort_value = a will assign a to sort_value making it an int instead of adding it to a list. sort_value = a将 a 分配给sort_value使其成为int而不是将其添加到列表中。

You need to sort the list after you insert items to it, and you need to append to the list instead of assigning it您需要在插入项目后对列表进行排序,并且您需要将 append 分配给列表而不是分配它

sort_value = []
chances = 1

while chances <= 5:
    a = int(input("Enter a number"))
    if a >= 0:
        sort_value.append(a)
        chances += 1

sort_value.sort()
print(sort_value)
sort_value = []
chances = 1
while chances <= 5:
    a = int(input("Enter a number"))
    if a >= 0:
        sort_value.append(a) 
        chances += 1
sort_value.sort()
print(sort_value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - 如何将值从 while 循环存储到 Pandas 数据帧中? - Python - How to store values from a while loop into a pandas dataframe? Python:如何将while循环的值之和存储到变量中? - Python:How to make the sum of the values of a while loop store into a variable? 在此 while 循环中,如何不接受除“是”或“否”以外的任何字符串值 - How do I accept no string values other than 'Yes' or 'No' in this while loop 如何在while循环中对列表进行排序 - how to sort a list in a while loop 是否可以在 while 循环中存储输入的值? - Is it possible to store inputted values in a while loop? 将 while 循环中生成的值存储在 python 中的列表中 - Store Values generated in a while loop on a list in python 如何使用 python 中的 while 循环按字母顺序排序? - How to sort alphabetically using the while loop in python? 如何运行while循环并仍然接受用户输入? - How can I run while loop and still accept user input? 如何在python中创建while循环输入以仅接受1或2作为输入? - how do create while loop input for accept only 1 or 2 as input in python? 如何使用 while 循环将值存储在字典中并将它们显示为 python 3.0 中的表? - How can I store values in a dictionary with a while loop and show them as a table in python 3.0?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM