def selection(alist):
sorted_list = []
while alist:
minimum = alist.pop(alist.index(min(alist)))
sorted_list.append(minimum)
print(sorted_list)
return sorted_list
a = [54,35,23,86,3546,87,43,7,2]
selection(a)
print(selection(a))
答案 0 :(得分:0)
尝试将函数调用分配给变量。这将允许您存储数据并在需要时调用它。
def selection(alist):
sorted_list = []
while alist:
minimum = alist.pop(alist.index(min(alist)))
sorted_list.append(minimum)
print(sorted_list)
return sorted_list
a = [54,35,23,86,3546,87,43,7,2]
value = selection(a)
print(value)
答案 1 :(得分:0)
这种情况正在发生,因为selection
正在弹出a
的所有值。如果你想保持a
原样,你应该将它克隆到一个临时数组并只操纵这个数组。
def selection(alist):
temp = list(alist)
sorted_list = []
while temp:
minimum = temp.pop(temp.index(min(temp)))
sorted_list.append(minimum)
return sorted_list
然后a
保持不变:
>>> selection(a)
[2, 7, 23, 35, 43, 54, 86, 87, 3546]
>>> print(selection(a))
[2, 7, 23, 35, 43, 54, 86, 87, 3546]
>>> a
[54, 35, 23, 86, 3546, 87, 43, 7, 2]
如果你的目标只是对这个数组进行排序,而你并不关心你是不是在编写排序算法,那么使用内置sorted
函数可能会更好(并且效率更高) of python:
>>> a = [54,35,23,86,3546,87,43,7,2]
>>> sorted(a)
[2, 7, 23, 35, 43, 54, 86, 87, 3546]
>>> a
[54, 35, 23, 86, 3546, 87, 43, 7, 2]
如果您想永久排序a
,请使用a.sort()
:
>>> a = [54,35,23,86,3546,87,43,7,2]
>>> a.sort()
>>> a
[2, 7, 23, 35, 43, 54, 86, 87, 3546]