首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >返回ValueError的numpy.argsort函数:要解压缩的值太多(应为1)

返回ValueError的numpy.argsort函数:要解压缩的值太多(应为1)
EN

Stack Overflow用户
提问于 2021-10-22 19:47:03
回答 1查看 32关注 0票数 0

我正在创建一个使用numpy.argsort对数据进行排序的函数。这是我的代码:

代码语言:javascript
运行
复制
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])

文档字符串返回:

代码语言:javascript
运行
复制
line 37, in sort_data
        ([x], [y]) = data
    ValueError: too many values to unpack (expected 1)

我认为这是因为函数接受包含两个列表的元组数据,但我不确定如何解决这个问题。如何让它正确返回?

EN

Stack Overflow用户

发布于 2021-10-22 20:07:16

解包为2个变量的效果很好:

代码语言:javascript
运行
复制
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]

但是你的尝试:

代码语言:javascript
运行
复制
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)

已更正:

代码语言:javascript
运行
复制
In [48]: ([x,y,z],w)=data
In [49]: x
Out[49]: 5

它无法将[5,1,7]解压到[x]中。

产生该错误的其他表达式:

代码语言:javascript
运行
复制
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)
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69682366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档