[英]How to iterate when you don't know if your object will be iterable
Sometimes I have multiple axes in axes[0]
, and sometimes just one. 有时我在
axes[0]
有多个轴,有时只有一个axes[0]
。 So to iterate over it/them, I use the following: 所以要迭代它/它们,我使用以下内容:
for ax,_x in [(axes[0], X[0])] if len(X)==1 else zip(axes[0],X):
What is the idiomatic way to do this? 这样做的惯用方法是什么?
In general, the best way is to just iterate. 通常,最好的方法是迭代。 Don't ask for permission (with
if
checks, rather wrap it in a try-except
block for handling the "forgiveness" cases. 不要求许可 (
if
检查,请将其包装在try-except
块中以处理“宽恕”案例。
As others have commented though, you shouldn't create different cases if X
is a list of size 1
, that still is iterable. 正如其他人所评论的那样,如果
X
是大小为1
的列表,那么你不应该创建不同的情况,它仍然是可迭代的。 If you use zip
it will stop at the shortest iterable: 如果您使用
zip
,它将以最短的可迭代次数停止:
>>> l = [1, 2, 3]
>>> y = [1, 2]
>>> list(zip(l, y))
[(1, 1), (2, 2)]
If you need to work with all values of the longer iterable and provide defaults for the missing values of the shorted one, use zip_longest
from itertools with an appropriate fillvalue
: 如果您需要的更长的迭代所有的值工作,为短路一个的遗漏值提供默认值,使用
zip_longest
从适当itertools fillvalue
:
>>> from itertools import zip_longest
>>> list(zip_longest(l, y, fillvalue=0))
[(1, 1), (2, 2), (3, 0)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.