Python 将 *args 转换为列表

问题描述 投票:0回答:4

这就是我要找的:

def __init__(self, *args):
  list_of_args = #magic
  Parent.__init__(self, list_of_args)

我需要将 *args 传递给单个数组,以便:

MyClass.__init__(a, b, c) == Parent.__init__([a, b, c])
python arrays python-2.7 args
4个回答
32
投票

没什么太神奇的:

def __init__(self, *args):
  Parent.__init__(self, list(args))

__init__
内部,变量
args
只是一个包含传入参数的元组。事实上,您可能可以只使用
Parent.__init__(self, args)
,除非您确实需要它是一个列表。

顺便说一句,使用

super()
优于
Parent.__init__()


10
投票

我在 senddex 教程中找到了一段处理此问题的代码:

https://www.youtube.com/watch?v=zPp80YM2v7k&index=11&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ

试试这个:

def test_args(*args):
    lists = [item for item in args]
    print lists

test_args('Sun','Rain','Storm','Wind')

结果:

[‘太阳’、‘雨’、‘暴风雨’、‘风’]


0
投票

如果您正在寻找与@simon的解决方案方向相同的东西,那么:

def test_args(*args):
    lists = [*args]
    print(lists)
test_args([7],'eight',[[9]])

结果:

[[7], '八', [[9]]]


0
投票

试试这个:

列表名称=列表(参数)

© www.soinside.com 2019 - 2024. All rights reserved.