- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在 Python 3 中,我如何检查一个对象是否是一个容器(而不是一个可能只允许通过一次的迭代器)?
这是一个例子:
def renormalize(cont):
'''
each value from the original container is scaled by the same factor
such that their total becomes 1.0
'''
total = sum(cont)
for v in cont:
yield v/total
list(renormalize(range(5))) # [0.0, 0.1, 0.2, 0.3, 0.4]
list(renormalize(k for k in range(5))) # [] - a bug!
显然,当 renormalize
函数接收到生成器表达式时,它不会按预期工作。它假定它可以多次遍历容器,而生成器只允许通过它一次。
理想情况下,我想这样做:
def renormalize(cont):
if not is_container(cont):
raise ContainerExpectedException
# ...
如何实现 is_container
?
我想我可以在我们开始第二次传递时检查参数是否为空。但是这种方法不适用于更复杂的函数,因为第二遍开始的确切时间并不明显。此外,我宁愿将验证放在函数入口处,而不是深入函数内部(并在函数被修改时四处移动)。
我当然可以重写 renormalize
函数以正确使用单遍迭代器。但这需要将输入数据复制到容器中。 “以防它们不是列表”复制数百万个大型列表对性能的影响是荒谬的。
编辑:我的原始示例使用了 weighted_average
函数:
def weighted_average(c):
'''
returns weighted average of a container c
c contains values and weights in tuples
weights don't need to sum up 1 (automatically renormalized)
'''
return sum((v * w for v, w in c)) / sum((w for v, w in c))
weighted_average([(0,1), (1,1)]) #0.5
weighted_average([(k, 1) for k in range(2)]) #0.5
weighted_average((k, 1) for k in range(2)) #mistake
但这不是最好的例子,因为重写为使用单次传递的 weighted_average
版本无论如何都可以说是更好的:
def weighted_average(it):
'''
returns weighted average of an iterator it
it yields values and weights in tuples
weights don't need to sum up 1 (automatically renormalized)
'''
total_value = 0
total_weight = 0
for v, w in it:
total_value += v
total_weight += w
return total_value / total_weight
最佳答案
虽然所有的可迭代对象都应该是 collections.Iterable 的子类,但不幸的是,并不是所有的都可以。这是基于对象实现的接口(interface)而不是它们“声明的”的答案。
简答:
你所说的“容器”,即一个可以多次迭代的列表/元组,而不是一个会耗尽的生成器,通常会同时实现 __iter__
和 __getitem__
。因此你可以这样做:
>>> def is_container_iterable(o):
... return hasattr(o, '__iter__') and hasattr(o, '__getitem__')
...
>>> is_container_iterable([])
True
>>> is_container_iterable(())
True
>>> is_container_iterable({})
True
>>> is_container_iterable(range(5))
True
>>> is_container_iterable(iter([]))
False
长答案:
但是,你可以做一个不会被穷尽且不支持getitem的iterable。例如,生成质数的函数。如果需要,您可以多次重复生成,但是拥有检索第 1065 个素数的函数需要大量计算,因此您可能不想支持它。 :-)
那么有没有更“靠谱”的方法呢?
好吧,所有可迭代对象都将实现一个 __iter__
函数,该函数将返回一个迭代器。迭代器将有一个 __next__
函数。这是迭代它时使用的内容。反复调用 __next__
最终会耗尽迭代器。
因此,如果它有一个 __next__
函数,它就是一个迭代器,并且会被耗尽。
>>> def foo():
... for x in range(5):
... yield x
...
>>> f = foo()
>>> f.__next__
<method-wrapper '__next__' of generator object at 0xb73c02d4>
还不是迭代器的可迭代对象将没有 __next__
函数,但会实现一个 __iter__
函数,该函数将返回一个可迭代对象:
>>> r = range(5)
>>> r.__next__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'range' object has no attribute '__next__'
>>> ri = iter(r)
>>> ri.__next__
<method-wrapper '__next__' of range_iterator object at 0xb73bef80>
因此您可以检查该对象是否具有 __iter__
但它没有 __next__
。
>>> def is_container_iterable(o):
... return hasattr(o, '__iter__') and not hasattr(o, '__next__')
...
>>> is_container_iterable(())
True
>>> is_container_iterable([])
True
>>> is_container_iterable({})
True
>>> is_container_iterable(range(5))
True
>>> is_container_iterable(iter(range(5)))
False
迭代器还有一个 __iter__
函数,它将返回 self。
>>> iter(f) is f
True
>>> iter(r) is r
False
>>> iter(ri) is ri
True
因此,您可以执行以下检查变体:
>>> def is_container_iterable(o):
... return iter(o) is not o
...
>>> is_container_iterable([])
True
>>> is_container_iterable(())
True
>>> is_container_iterable({})
True
>>> is_container_iterable(range(5))
True
>>> is_container_iterable(iter([]))
False
如果您实现一个返回损坏的迭代器的对象,那将失败,当您再次对其调用 iter() 时,该迭代器不返回 self。但是你的(或第三方模块)代码实际上做错了。
虽然它确实依赖于制作一个迭代器,因此调用对象 __iter__
,这在理论上可能有副作用,而上面的 hasattr 调用不应该有副作用。好的,所以它调用了可能有的getattribute。但是你可以这样解决:
>>> def is_container_iterable(o):
... try:
... object.__getattribute__(o, '__iter__')
... except AttributeError:
... return False
... try:
... object.__getattribute__(o, '__next__')
... except AttributeError:
... return True
... return False
...
>>> is_container_iterable([])
True
>>> is_container_iterable(())
True
>>> is_container_iterable({})
True
>>> is_container_iterable(range(5))
True
>>> is_container_iterable(iter(range(5)))
False
这个是相当安全的,并且应该在所有情况下都有效,除非对象在 __getattribute__
调用上动态生成 __next__
或 __iter__
,但是如果你这样做,你就是疯了。 :-)
本能地,我的首选版本是 iter(o) is o
,但我从来不需要这样做,所以这不是基于经验。
关于python - 如何检查可迭代对象是否允许多次通过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8993305/
我有一个 if 语句,如下所示 if (not(fullpath.lower().endswith(".pdf")) or not (fullpath.lower().endswith(tup
然而,在 PHP 中,可以: only appears if $foo is true. only appears if $foo is false. 在 Javascript 中,能否在一个脚
XML有很多好处。它既是机器可读的,也是人类可读的,它具有标准化的格式,并且用途广泛。 它也有一些缺点。它是冗长的,不是传输大量数据的非常有效的方法。 XML最有用的方面之一是模式语言。使用模式,您可
由于长期使用 SQL2000,我并没有真正深入了解公用表表达式。 我给出的答案here (#4025380)和 here (#4018793)违背了潮流,因为他们没有使用 CTE。 我很欣赏它们对于递
我有一个应用程序: void deleteObj(id){ MyObj obj = getObjById(id); if (obj == null) { throw n
我的代码如下。可能我以类似的方式多次使用它,即简单地说,我正在以这种方式管理 session 和事务: List users= null; try{ sess
在开发J2EE Web应用程序时,我通常会按以下方式组织我的包结构 com.jameselsey.. 控制器-控制器/操作转到此处 服务-事务服务类,由控制器调用 域-应用程序使用的我的域类/对象 D
这更多是出于好奇而不是任何重要问题,但我只是想知道 memmove 中的以下片段文档: Copying takes place as if an intermediate buffer were us
路径压缩涉及将根指定为路径上每个节点的新父节点——这可能会降低根的等级,并可能降低路径上所有节点的等级。有办法解决这个问题吗?有必要处理这个吗?或者,也许可以将等级视为树高的上限而不是确切的高度? 谢
我有两个类,A 和 B。A 是 B 的父类,我有一个函数接收指向 A 类型类的指针,检查它是否也是 B 类型,如果是将调用另一个函数,该函数接受一个指向类型 B 的类的指针。当函数调用另一个函数时,我
有没有办法让 valgrind 使用多个处理器? 我正在使用 valgrind 的 callgrind 进行一些瓶颈分析,并注意到我的应用程序中的资源使用行为与在 valgrind/callgrind
假设我们要使用 ReaderT [(a,b)]超过 Maybe monad,然后我们想在列表中进行查找。 现在,一个简单且不常见的方法是: 第一种可能性 find a = ReaderT (looku
我的代码似乎有问题。我需要说的是: if ( $('html').attr('lang').val() == 'fr-FR' ) { // do this } else { // do
根据this文章(2018 年 4 月)AKS 在可用性集中运行时能够跨故障域智能放置 Pod,但尚不考虑更新域。很快就会使用更新域将 Pod 放入 AKS 中吗? 最佳答案 当您设置集群时,它已经自
course | section | type comart2 : bsit201 : lec comart2 :
我正在开发自己的 SDK,而这又依赖于某些第 3 方 SDK。例如 - OkHttp。 我应该将 OkHttp 添加到我的 build.gradle 中,还是让我的 SDK 用户包含它?在这种情况下,
随着 Rust 越来越充实,我对它的兴趣开始激起。我喜欢它支持代数数据类型,尤其是那些匹配的事实,但是对其他功能习语有什么想法吗? 例如标准库中是否有标准过滤器/映射/归约函数的集合,更重要的是,您能
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 关闭 9 年前。 Improve
我一直在研究 PHP 中的对象。我见过的所有示例甚至在它们自己的对象上都使用了对象构造函数。 PHP 会强制您这样做吗?如果是,为什么? 例如: firstname = $firstname;
...比关联数组? 关联数组会占用更多内存吗? $arr = array(1, 1, 1); $arr[10] = 1; $arr[] = 1; // <- index is 11; does the
我是一名优秀的程序员,十分优秀!