我想要一个通常接受 X 类型参数的函数,其中 X 是标量、列表或字典,并根据其他信息返回具有相同键值的 X 列表。
def foo(info, k):
return [bar(item,k) for item in processInfo(info)]
def bar(item, keydata):
# pseudocode follows.
# What we want to do is return an output of parallel type to the input key k,
# using the key data to lookup information from the input item.
if keydata is a scalar:
return item[keydata]
elif keydata is a list:
return [item[k] for k in keydata]
elif keydata is a dict:
return dict((k,item[v]) for (k,v) in keydata.iteritems())
else:
raise ValueError('bar expects a scalar, list, or dict')
我的问题是,如何在这三种类型之间进行调度?
编辑:字符串将被解释为标量,而不是列表/可迭代对象。元组将被解释为可迭代的。
编辑 2:我想要鸭子打字,而不是严格打字。
最佳答案
您需要按正确的顺序执行操作,因为 str
和 dict
类型是可迭代的。
from collections import Iterable, Mapping # in Python 3 use from collections.abc
def bar(item, keydata):
if isinstance(keydata, Mapping):
return {k: item[v] for (k,v) in keydata.iteritems()}
elif isinstance(keydata, Iterable) and not isinstance(keydata, str):
return [item[k] for k in keydata]
return item[keydata]
关于python - 在 Python 中区分标量、列表和字典参数的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201890/