【问题标题】:Python3- How to call a function that accepts *args variably [duplicate]Python3-如何调用可变接受*args的函数[重复]
【发布时间】:2017-02-24 01:34:34
【问题描述】:

一般问题

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

我是自学python;我不禁认为我错过了一些关于 *args 工作原理的相当基本的东西。随时向我指出一些必要的阅读。

具体问题

当使用 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))

当然,这可以正常工作。

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

即:

indices = {insert some code here to provide itemgetter() what it needs} records.sort(key=operator.itemgetter(indices))

我试过了:

元组:

indices = (3, 1) 要么 indices = 3, 1

TypeError: list indices must be integers or slices, not tuple

列表:

indices = [3, 1]

TypeError: list indices must be integers or slices, not list

对基础知识感到谦卑永远不会太晚。在此先感谢您协助填补我的 python 基础中的这一空白。

【问题讨论】:

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


【解决方案1】:

假设你有

indices = [3, 1]

你可以使用 Python 解包给函数调用 3 和 1:

itemgetter(*indices)

这相当于

itemgetter(3, 1)

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

【讨论】:

    猜你喜欢
    • 2011-03-08
    • 2013-08-07
    • 2021-05-16
    • 1970-01-01
    • 2020-09-18
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多