按功能对列表进行排序会导致错误的结果 [英] Sorting a list by function leads to wrong result

查看:94
本文介绍了按功能对列表进行排序会导致错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在函数中将列表作为参数传递时,为什么以下列表没有更改?

When passing a list as an argument in function, why is the following list not changed?

def foo(*x):
    y=sorted(x)
    print(y)

a=[3,2,1]

该函数返回[[3, 2, 1]],而不是[[1,2,3]].为什么会这样呢?这与按值调用有关吗?

The function is returning [[3, 2, 1]], not [[1,2,3]]. Why is this happening? Is this something to do with call by value?

推荐答案

因为函数的参数指定为* a,这就像说您的参数是未定义维的元组

because the argument of your function is specified as *a, which is like saying your argument is a tuple of undefined dimension

当您尝试对带有嵌套列表的元组进行排序时,该值不会更改

when you try to sort a tuple with a nested list, the value will not change

事实上,您获得了列表列表(您获得了[[3,2,1]]而不是[3,2,1])

infact as result you got a list of list (you got [[3, 2, 1]] not [3, 2, 1])

如果您尝试这样做,它将起作用

if you try this, it will work

def foo(*x): 
    y=sorted(x[0]) 
    print(y)

这篇关于按功能对列表进行排序会导致错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆