python - 在 Python 中区分标量、列表和字典参数的最佳方法?

标签 python types python-2.7 polymorphism

我想要一个通常接受 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:我想要鸭子打字,而不是严格打字。

最佳答案

您需要按正确的顺序执行操作,因为 strdict 类型是可迭代的。

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/

相关文章:

python - 使用python从图像中提取形状

Python。重写方法而不创建派生类并调用原始方法

python - 垃圾日志问题

python - 否则缩进错误: unexpected unindent in PyCharm

python - django 中的表单验证

haskell - Haskell中的实际类型与预期类型错误

function - 运算符的 Haskell 类型优先级高于函数

JAVA——原始类型 VS 对象类型

python-2.7 - pylint 找不到 google.cloud

python - numpy 的参数方程