简体   繁体   English

当你不知道你的对象是否可以迭代时如何迭代

[英]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.

相关问题 我不知道为什么有'gurobipy.LinExpr' object is not iterable - I don't know why there is 'gurobipy.LinExpr' object is not iterable TypeError: 'int' object 不可迭代,不知道为什么会这样 - TypeError: 'int' object is not iterable, don't know why this is happening 不知道最终大小时如何构建数组? - How to build an array when you don't know the final size? 当您不知道有多少列时将CSV转换为SQLite - Convert CSV to SQLite when your don't know how many columns there are 如果您不知道嵌套数组的嵌套程度,有没有办法在嵌套数组中获取对象的索引 - Is there a way to grab the index of an object in a nested array if you don't know how nested it is 当你不知道有多少循环需要嵌套时,如何处理嵌套循环(python 3.4)? - How to deal with nested loops when you don't know how many loops need nesting (python 3.4)? 当你不知道将要有多少部分时,如何获得字符串的单独部分 - How to obtain the separate parts of a string when you don't know the amount of parts there will be 不知道服务器IP时如何使用Python SMB连接? - How to use Python SMB connection when you don't know the server's IP? 当您不知道确切位置时,如何在 DF 中对字符串的一部分进行切片? - How to slice a part of a string in DF when you don't know exact position? “'int' object 不可迭代” - 如何迭代 integer? - "'int' object is not iterable" - How to iterate over an integer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM