gpt4 book ai didi

python - 检查两个生成器的不同之处

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:06 25 4
gpt4 key购买 nike

为简单起见,假设我有两个生成器:

it1 = iter([1,2,3,4])
it2 = iter([1,2,10,20])

了解第一个差异(位置 2)在哪里或它们是否相等的最佳方法是什么?我想避免显式循环:

for pos, v1, v2 in enumerate(izip(it1, it2)):
if v1 != v2: return pos
return None

并使用函数式编程:

try:
return next(pos for pos, (v1, v2) in enumerate(izip(it1, it2)) if v1 != v2)
except StopIteration:
return None

关键是我使用的解决方案很丑陋,比显式循环更冗长,...

你能做得更好吗?

最佳答案

您可以通过为 next 提供默认值来简化第二个示例:

return next((pos for pos, (v1, v2) in enumerate(izip(it1, it2)) if v1 != v2), None)

来自docs :

next(iterator[, default])

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

关于python - 检查两个生成器的不同之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com