Numbers = []
QN = input("what are the numbers")
Numbers.append(QN)
def Median():
median = sorted(Numbers)
print ("Sorted:", median)
Median()
这是我的代码,我正在尝试创建一个程序,在该程序中,用户输入一个数字列表,而不是该程序使用排序功能从最小到最大列出它们。问题在于它没有打印排序列表,而是在打印原始的未排序列表。我无法弄清楚问题,用户输入的数字列表已添加到列表中,但似乎该列表未排序。
答案 0 :(得分:0)
sorted函数接受一个列表并对其元素进行排序。 所以,
In [2]: sorted([1])
Out[2]: [1]
一个元素的列表已被视为已排序,因为一个数字没有顺序。
In [1]: sorted([312,321,213])
Out[1]: [213, 312, 321]
这三个被视为数字,并进行了相应的排序。
In [2]: sorted(['312','33','321'])
Out[2]: ['312', '321', '33']
有被认为是字符串,并按字母顺序按字母顺序
排序In [3]: sorted('231')
Out[3]: ['1', '2', '3']
字符串也被视为字符列表,因此字符按字母顺序排序。
QN = input("what are the numbers")
def Median():
median = sorted(QN)
print ("Sorted:", median)
Median()
这是使当前代码正常工作的方式。
但这可能是您想要做的:
def Median(lst):
median = sorted(lst)
return median # you have to work on this further to actually calculate the median, this will just return the sorted list.
Numbers = []
QN = 'placeholder' # put a placeholder so we can enter the loop
print('enter your numbers, one number in each line, empty line to end')
while (QN != ''):
QN = input()
if (QN != ''):
Numbers.append(int(QN)) # make sure you put the int() because you don't want to consider the numbers as strings because in that case they will be sorted alphabetically.
print ("Sorted:", Median(Numbers))
结果:
enter your numbers, one number in each line, empty line to end
1
32
23
21
24
Sorted: [1, 21, 23, 24, 32]
答案 1 :(得分:0)
import time
Numbers = []
A = int(input("how many numbers are in the list"))
time.sleep(.5)
print ("Can you please enter the numbers?")
time.sleep(.3)
for i in range(A):
data = int(input())
Numbers.append(data)
def Median():
median = sorted(Numbers)
print median
if A%2 == 0:
one = int(A/2) - 1
two = one + 1
One = median[one]
Two = median[two]
sum = (One + Two)
Ans = sum/2
print ("The median is " + str(Ans))
else:
one = int(A/2)
One = median[one]
print ("The median is " + str(One))
这似乎有效。这段代码行吗?