我的return语句返回空字符串,但打印它返回正确的值

时间:2017-10-05 16:39:55

标签: python

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))

2 个答案:

答案 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]