我正在创建一个使用numpy.argsort对数据进行排序的函数。这是我的代码:
import numpy as np
## 1. Complete sort_data
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])
"""
([x], [y]) = data
xarray = np.array(x)
yarray = np.array(y)
xx = np.argsort(xarray)
yy = np.argsort(yarray)
xsort = xarray[xx]
ysort = yarray[yy]
return ([xsort],[ysort])
文档字符串返回:
line 37, in sort_data
([x], [y]) = data
ValueError: too many values to unpack (expected 1)
我认为这是因为函数接受包含两个列表的元组数据,但我不确定如何解决这个问题。如何让它正确返回?
发布于 2021-10-22 20:07:16
解包为2个变量的效果很好:
In [42]: data = ([5, 1, 7], [1, 2, 3])
In [43]: x,y=data
In [44]: x
Out[44]: [5, 1, 7]
In [45]: (x,y)=data
In [46]: y
Out[46]: [1, 2, 3]
但是你的尝试:
In [47]: ([x],[y])=data
Traceback (most recent call last):
File "<ipython-input-47-9f88af1e8960>", line 1, in <module>
([x],[y])=data
ValueError: too many values to unpack (expected 1)
已更正:
In [48]: ([x,y,z],w)=data
In [49]: x
Out[49]: 5
它无法将[5,1,7]
解压到[x]
中。
产生该错误的其他表达式:
In [50]: [x]=[5,1,7]
Traceback (most recent call last):
File "<ipython-input-50-18b1033808bd>", line 1, in <module>
[x]=[5,1,7]
ValueError: too many values to unpack (expected 1)
In [51]: x,=[5,1,7]
Traceback (most recent call last):
File "<ipython-input-51-da60f4d5d887>", line 1, in <module>
x,=[5,1,7]
ValueError: too many values to unpack (expected 1)
https://stackoverflow.com/questions/69682366
复制相似问题