Python3-如何调用可变地接受 *args 的函数

标签 python python-3.x arguments parameter-passing

<分区>

一般问题

调用接受 *args 的函数的 python3.5+ 语法是什么,其中 *args 引用具有多项的变量。

I am self taught python; I can't help but think I am missing something rather elementary about how *args works. Feel free to point me to some necessary reading.

一个具体问题

当使用 operator.itemgetter(*items) 按列对列表列表进行排序时,如何可变地提供 *items?

示例列表

import operator

records = [
    ['0055613893 ', 'AP', 'BU', 'AA', '00005000012404R'],
    ['0048303110 ', 'MM', 'BU', 'AB', '00028230031385R'],
    ['0044285346 ', 'AP', 'BU', 'AA', '00062240050078R'],
    ['0048303108 ', 'MO', 'BU', 'AF', '00047780036604R'],
    ['0048751228 ', 'AP', 'ME', 'AC', '00000750013177R'],
    ['0045059521 ', 'AR', 'YT', 'AB', '00005430014570R']
]

如果我想按第 3 列然后按第 1 列对这个特定的记录集进行排序,我会:

records.sort(key=operator.itemgetter(3, 1))

当然,这会像人们预期的那样工作。

我的意思是如何向 itemgetter() 可变地提供“3、1”?

即:

indices = {在此处插入一些代码以提供 itemgetter() 所需的内容} records.sort(key=operator.itemgetter(indices))

我试过:

元组:

指数 = (3, 1) 或者 指数 = 3, 1

类型错误:列表索引必须是整数或切片,而不是元组

列表:

指数 = [3, 1]

类型错误:列表索引必须是整数或切片,而不是列表

It's never too late to be humbled by the basics. Thanks in advance for assisting in filling this gap in my python foundation.

最佳答案

假设你有

indices = [3, 1]

您可以使用 Python 解包将 3 和 1 提供给函数调用:

itemgetter(*indices)

这相当于

itemgetter(3, 1)

我不确定它适用于哪个版本的 Python。这是快速变化的部分之一,因此如果您使用的是旧版本,则可能需要阅读一些内容。

关于Python3-如何调用可变地接受 *args 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046209/

相关文章:

python - 根据相同相邻值的序列拆分 numpy 数组

python - 将 numpy unicode 数组写入文本文件

javascript - 从本地 JavaScript 应用程序调用 Python 脚本

python - 如何在 3 个字符串的所有可能组合上运行代码

Python Generator 内存对大量读数有好处吗?

python-3.x - ValueError : The number of FixedLocator locations (5), 通常来自对 set_ticks 的调用,与刻度标签的数量不匹配 (12)

python - 值错误: No data provided for "dense_input"

c - C 中函数参数的自省(introspection)是否可能?

Python - 干净地传递参数

objective-c - 如何将参数传递给 NSTimer 中调用的方法