首页 > 解决方案 > 为单个元素提供可迭代

问题描述

我有一个包含对象的列表或相同对象的另一个列表:

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)

标签: pythoniteration

解决方案


我找到了答案。

只需在OrderLine类中编写以下方法:

def __iter__(self):
    return iter((self,))

推荐阅读