【发布时间】:2016-09-27 17:02:41
【问题描述】:
我正在尝试根据每个元素的第一项对列表列表进行排序:
def getKey(item):
return item[0]
def myFun(x):
return sorted(x, key= getKey(x))
my_x = [[1,100], [5,200], [3,30]]
myFun(my_x)
我希望根据每个元素的第一项进行排序,即 1、5 和 3。预期结果应该是:[[1,100], [3,30], [5,200]]
但是,我收到以下错误:
TypeErrorTraceback (most recent call last)
<ipython-input-7-4c88bbc1a944> in <module>()
3
4 my_x = [[1,100], [5,200], [3,30]]
----> 5 myFun(my_x)
<ipython-input-7-4c88bbc1a944> in myFun(x)
1 def myFun(x):
----> 2 return sorted(x, key= getKey(x))
3
4 my_x = [[1,100], [5,200], [3,30]]
5 myFun(my_x)
TypeError: 'list' object is not callable
知道我在这里做错了什么吗?谢谢!
【问题讨论】:
-
什么是
getKey? -
我想你想要
key=operator.itemgetter(0) -
@inspectorG4dget 这甚至不需要。这是
sorted的默认行为。 -
对不起,我有 getKey,忘了把它放在问题中。请参阅编辑。
标签: python list python-2.7 sorting