列表和解压缩列表的功能

时间:2017-10-10 10:41:14

标签: python python-3.x

我有两种可能的方法来调用函数。

列表:

some_list = [1,2,3,4]
my_function(some_list)

使用解压缩列表或只有多个参数:

my_function(*some_list) == my_function(1,2,3,4)

也等于第一种情况:

my_function(some_list) == my_function(*some_list) == my_function(1,2,3,4)

在函数my_function中,我想迭代列表。所以对于frist情况,函数看起来像这样:

def my_function(arg):
    for i in arg:
         # do something

现在对于第二种情况,我将重新打包解压缩列表,产生以下功能:

def my_function(*arg):
    for i in arg:
        # do something

有两种方法可以为这两种情况提供一个好的单一功能吗?

1 个答案:

答案 0 :(得分:2)

你可以创建一个autounpacking checker装饰器来包装函数:

import functools


def autounpack(f):
  @functools.wraps(f)
  def wrapped(*args):
    if len(args) == 1 and type(args[0]) == list:
      return f(*args[0])
    else:
      return f(*args)
  return wrapped


@autounpack
def my_f(*args):
  print(args)

这里有live example