我试图在初始化对象时遍历与对象关联的每个数字(并打印),但仅返回第一个元素,而不返回其他元素。但这对于正常的for循环应该有用吗?
class Test():
def __init__(self):
self.data = [1,2,3,4,5,6,7,8]
def listelements(self):
for i in self.data:
return [i]
a = Test()
print(a.listelements())
答案 0 :(得分:1)
尝试使用yield
代替下面的return
,
>>> class Test():
def __init__(self):
self.data = [1,2,3,4,5,6,7,8]
def listelements(self):
for i in self.data:
yield [i]
>>> a = Test()
>>> print(a.listelements()) # you can iterate through this generator
<generator object Test.listelements at 0x00000220E0D03E08>
输出:
>>> for element in a.listelements():
print(element)
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
答案 1 :(得分:1)
否,return
会中断for循环,但yield
不会。请查看python生成器here
class Test():
def __init__(self):
self.data = [1, 2, 3, 4, 5, 6, 7, 8]
def listelements(self):
for i in self.data:
yield i
a = Test()
print(list(a.listelements())) # [1, 2, 3, 4, 5, 6, 7, 8]