【发布时间】:2021-12-13 03:15:51
【问题描述】:
我正在创建一个函数,它接收两个列表和一个元组作为数据,并返回相对于第一个列表索引按升序排序的数据(这对我的问题不是很重要,而是上下文。)这里是我有什么:
def sort_data(data):
""" (tuple) -> tuple
data is a tuple of two lists.
Returns a copy of the input tuple sorted in
non-decreasing order with respect to the
data[0]
>>> sort_data(([5, 1, 7], [1, 2, 3]))
([1, 5, 7], [2, 1, 3])
>>> sort_data(([2, 4, 8], [1, 2, 3]))
([2, 4, 8], [1, 2, 3])
>>> sort_data( ([11, 4, -5], [1, 2, 3]))
([-5, 4, 11], [3, 2, 1])
"""
([a,b,c],[d,e,f]) = data
x = [a,b,c]
y = [d,e,f]
xarray = np.array(x)
yarray = np.array(y)
x1 = np.argsort(xarray)
xsort = (xarray[x1])
ysort = (yarray[x1])
#remove array()
return ([xsort],[ysort])
这很好用,但返回的错误非常轻微。例如,我希望在我的文档字符串中看到这个:
>>> sort_data(([5, 1, 7], [1, 2, 3]))
([1, 5, 7], [2, 1, 3])
但我得到了这个:
([array([1, 5, 7])], [array([2, 1, 3])])
如何删除 array() 以便将元组中的两个列表作为返回值?我试图将它转换为一个元组,但是当我只想要一个时,它是两个元组。
【问题讨论】:
-
试试
return (xsort.tolist(), ysort.tolist()) -
@James 辛苦了,谢谢!!
-
你为什么要关心这个?您将数据的表示与数据的内容混淆了。数据在这两种情况下都同样可用,只是打印方式不同,使用你的例程的人可能希望它作为一个 numpy 数组。
-
而且您根本不需要 a,b,c,d,e,f 变量。只需执行
xarray = np.array(data[0])/yarray = np.array(data[1])。
标签: python arrays numpy return