python - 为单个元素提供可迭代
问题描述
我有一个包含对象的列表或相同对象的另一个列表:
class OrderLine:
pass
lines = [OrderLine(), [OrderLine(), OrderLine()]]
def process_line(line):
pass
当我查询列表时,我需要从 collections.abc import Iterable 执行以下操作
index = 0
line = lines[index]
if isinstance(line, Iterable):
for _line in line:
process_line(_line)
else:
process_line(line)
我的问题是,我怎样才能编写 OrderLine 类,这样我就不必检查类型了。如果我从列表中获得 OrderLine,则循环将进入一次,如果我获得 Iterable,则循环将进入更多次。喜欢:
index = 0
line = lines[index]
for _line in line:
process_line(_line)
解决方案
我找到了答案。
只需在OrderLine
类中编写以下方法:
def __iter__(self):
return iter((self,))
推荐阅读
- javascript - 是否可以在 jQuery 中将多个 HTML 元素合并到一个脚本中?
- php - Yii2 JUI datepicker 从输入字段中删除 HTML 属性
- bash - 在jenkins命令shell中的bash文件中运行commnad时无法克隆repo但是当我直接在jenkins命令shell中运行时它可以工作
- emacs - 呈现当前待办事项的上一个和下一个关系
- swiftui - SwiftUI Picker 视图在 TabView 中消失
- selenium - 错误:无法从以下位置确定类型:<。最后 1 个字符读取:<
- java - java - 如何根据用户输入从java中的链表中删除特定元素?
- javascript - 使用 Summer note 编辑存储在数据库中的 HTML + CSS
- python - 在databricks中导入python依赖项(无法导入模块)
- flutter - Flutter:local_auth:^0.6.1:PlatformException(错误,您需要在此活动中使用 Theme.AppCompat 主题(或后代)。,null)