【发布时间】:2015-02-06 04:04:12
【问题描述】:
我正在尝试编写代码,该代码可以按未知数量的键对列表列表进行排序,每个键都有一个相关的布尔值,对应于排序是升序还是降序。
我让它按升序或降序对所有键进行排序,如下所示:
import operator
def sort2D(table, *params):
table.sort(key=operator.itemgetter(*params), reverse = True)
return table
table = sort2D(table, *listOfKeys)
我也不确定如何将布尔值输入到该函数中。当我尝试为第二个输入列表执行类似代码时,出现语法错误,如下所示:
import operator
def sort2D(table, *params, *args): #this is the line that causes the syntax error
table.sort(key=operator.itemgetter(*params), reverse = *args)
return table
table = sort2D(table, *listOfKeys, *listOfBools)
我可以看出错误是因为我误用 *、*params 和 *args 将列表输入到函数中,但我不知道如何输入第二个列表而没有类似于那。是否可以将第二个列表输入到我拥有的函数中,还是我必须做一些完全不同的事情才能完成我想要的?
编辑:我想要的输入和输出示例如下所示:
['Smith', 'Bob', 4, 3.75, 'Blue']
['Jones', 'Tom', 17, 0.44, 'Blue']
['Smith', 'John', 3, 2.22, 'Yellow']
['Jones', 'Drew', 5, 6.74, 'Red']
如果按姓氏降序然后按整数升序排序,则 params 将是 [0, 2] 对应的列,bools 将是 [True, False]。输出如下所示:
['Smith', 'John', 3, 2.22, 'Yellow']
['Smith', 'Bob', 4, 3.75, 'Blue']
['Jones', 'Drew', 5, 6.74, 'Red']
['Jones', 'Tom', 17, 0.44, 'Blue']
【问题讨论】:
-
您不需要使用参数打包 (
*) 将列表传递给函数。 -
如果你给出一个你想要的输入和输出的具体例子会有所帮助。
标签: python list sorting python-3.x