我有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
但我一直在寻求解决方案。
答案 0 :(得分:2)
有几种可行的方法。您可以检查输入的类型:它是元组还是列表。或者你可以随时使用它作为列表。
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'})]
根据您的行为,这两种方法可能都有用或无用。
答案 1 :(得分:1)
您寻求的模式是 multimethod 。我在PyPI中找到了几个实现,但使用了Guido van Rossum编写的简单模块:Five-minute Multimethods in 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'})])