简体   繁体   English

如何在Python中区分参数类型(元组/元组列表)

[英]How to distinguish argument types (tuple/list of tuples) in Python

I have getDict() function that should accept tuple or list of tuples: 我有应该接受元组或元组列表的getDict()函数:

def getDict(items):
    item1,item2=items
    print item1,item2

getDict(({1:'a'},{2:'b'}))
getDict([({1:'a'},{2:'b'})])

But it gives me an error: 但这给了我一个错误:

ValueError: need more than 1 value to unpack

I know that it can be fixed with following snipped: 我知道可以通过以下代码修复它:

if type(items) == list:
    item1,item2=items[0]
else:
    item1,item2=items

But I'm seeking for a solution without if. 但是我正在寻找一个没有if的解决方案。

There are several possible ways to do it. 有几种可能的方法。 You can check a type of your input: is it a tuple or a list. 您可以检查输入的类型:是元组还是列表。 Or you can always use it a as list. 或者,您始终可以将其用作列表。

def get_dict_cast(tuple_or_list):
    """ This function casts it's args to list. """
    now_list = list(tuple_or_list)
    print(now_list, now_list.__class__) 

def get_dict_type_check(input):
    """ 
    This function checks what to do with your input depending on it's type.
    """
    if isinstance(input, tuple):
         print('it is a tuple: {}'.format(input))
    elif isinstance(input, list):
         print('it is a list: {}'.format(input))

just_tuple = ({ 1: 'a' }, { 2: 'b' })
list_of_tuples = [
    just_tuple, 
    ({ 3: 'a' }, { 2: 'b' })
]

get_dict_cast(just_tuple)
get_dict_cast(list_of_tuples)

get_dict_type_check(just_tuple)
get_dict_type_check(list_of_tuples)

The output will be: 输出将是:

# get_dict_cast(just_tuple):
[{1: 'a'}, {2: 'b'}], <type 'list'>

# get_dict_cast(list_of_tuples):
[({1: 'a'}, {2: 'b'}), ({3: 'a'}, {2: 'b'})], <type 'list'>

# get_dict_type_check functions:
it is a tuple: ({1: 'a'}, {2: 'b'})
it is a list: [({1: 'a'}, {2: 'b'}), ({3: 'a'}, {2: 'b'})]

Depending on what your are doing both methods might be usefull or useless. 取决于您在做什么,这两种方法可能有用或无用。

The pattern you seeking is multimethod . 你追求的模式是多重方法 I have found several implementations in PyPI, but used simple module written by Guido van Rossum: Five-minute Multimethods in Python 我在PyPI中找到了几种实现,但是使用了Guido van Rossum编写的简单模块: Python中的五分钟多方法

They can be easily used like this: 它们可以像这样容易使用:

@multimethod(tuple)
def getDict(items):
    item1,item2=items
    print item1,item2

@multimethod(list)
def getDict(items):
    return getDict(items[0])

getDict(({1:'a'},{2:'b'}))
getDict([({1:'a'},{2:'b'})])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM