[英]How to distinguish argument types (tuple/list of tuples) in Python
我有应该接受元组或元组列表的getDict()
函数:
def getDict(items):
item1,item2=items
print item1,item2
getDict(({1:'a'},{2:'b'}))
getDict([({1:'a'},{2:'b'})])
但这给了我一个错误:
ValueError: need more than 1 value to unpack
我知道可以通过以下代码修复它:
if type(items) == list:
item1,item2=items[0]
else:
item1,item2=items
但是我正在寻找一个没有if的解决方案。
有几种可能的方法。 您可以检查输入的类型:是元组还是列表。 或者,您始终可以将其用作列表。
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)
输出将是:
# 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'})]
取决于您在做什么,这两种方法可能有用或无用。
你追求的模式是多重方法 。 我在PyPI中找到了几种实现,但是使用了Guido van Rossum编写的简单模块: Python中的五分钟多方法
它们可以像这样容易使用:
@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.