python - 迭代python中的列表或单个元素

标签 python

我想迭代一个未知函数的输出。不幸的是,我不知道该函数是返回单个项目还是一个元组。这一定是一个标准问题,并且必须有一个标准的方法来处理这个问题——我现在所拥有的非常丑陋。

x = UnknownFunction()
if islist(x):
    iterator = x
else:
    iterator = [x]

def islist(s):
    try:
        len(s)
        return True
    except TypeError:
        return False

for ii in iterator:
    #do stuff

最佳答案

这个问题最通用的解决方案是使用带有抽象基类collections.Iterableisinstance

import collections

def get_iterable(x):
    if isinstance(x, collections.Iterable):
        return x
    else:
        return (x,)

您可能还想测试 basestring 以及 Kindall建议。

    if isinstance(x, collections.Iterable) and not isinstance(x, basestring):

现在有些人可能会想,就像我曾经做过的那样,“难道不是 isinstance considered harmful 吗?它不会将你锁定为使用一种类型吗?不会使用 hasattr(x, '__iter__') 会更好吗?"

答案是:对于抽象基类来说不是这样。实际上,您可以使用 __iter__ 方法定义自己的类,它会被识别为 collections.Iterable 的实例,即使您没有子类 collections.Iterable。这是因为 collections.Iterable 定义了 __subclasshook__它通过它实现的任何定义来确定传递给它的类型是否是 Iterable。

>>> class MyIter(object):
...     def __iter__(self):
...         return iter(range(10))
... 
>>> i = MyIter()
>>> isinstance(i, collections.Iterable)
True
>>> collections.Iterable.__subclasshook__(type(i))
True

关于python - 迭代python中的列表或单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6710834/

相关文章:

python - 整数值加 1 会产生 TypeError

python - Pandas 样式格式不将列格式化为带小数位的百分比

python - Google App Engine 数据库查询内存使用情况

python - PLY:需要帮助理解 LALR 解析器如何解析给定语法的输入

python - 具有 Statsmodel ValueError : zero-size array to reduction operation maximum which has no identity 的多重 OLS 回归

Python:将 GIF 转换为视频(mp4)

python - 如何在集群上启用 MPI 的应用程序中使用 scipy.weave.inline?

python - 如何使用 pandas 转置完整文件

python - 将对 Python Twisted 透视代理的远程调用排队?

python - 理解 Python 交换 : why is a, b = b, a 并不总是等价于 b, a = a, b?