【问题标题】:Python converting *args to listPython 将 *args 转换为列表
【发布时间】:2013-03-07 12:19:32
【问题描述】:

这就是我要找的:

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])

【问题讨论】:

  • 你的意思是:Parent.__init__(list(args)) ?
  • 您可能不需要一个列表,而是一个序列。 args 已经是一个元组
  • 您不仅限于序列,还可以采用可迭代对象。我不确定从什么时候开始,至少从PEP-448.

标签: python arrays python-2.7 args


【解决方案1】:

没什么太神奇的:

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

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

附带说明,使用super() 优于Parent.__init__()

【讨论】:

    【解决方案2】:

    我在 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')
    

    结果:

    ['太阳','雨','风暴','风']

    【讨论】:

      【解决方案3】:

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

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

      结果:

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

      【讨论】:

        猜你喜欢
        • 2010-10-24
        • 2023-03-09
        • 1970-01-01
        • 2018-01-17
        • 2022-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-05
        相关资源
        最近更新 更多