遍历对象的列表数据

时间:2019-11-11 04:13:50

标签: python-3.x

我试图在初始化对象时遍历与对象关联的每个数字(并打印),但仅返回第一个元素,而不返回其他元素。但这对于正常的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())

2 个答案:

答案 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]