【问题标题】:How do I access an object's attribute while iterating through a nested list in Python?如何在 Python 中遍历嵌套列表时访问对象的属性?
【发布时间】:2014-04-03 16:56:37
【问题描述】:

我有一个对象定义如下:

class word(object): #object class

    def __init__(self, originalWord=None, azWord=None, wLength=None):
        self.originalWord = originalWord
        self.azWord = azWord
        self.wLength = wLength

我有一个名为 results[] 的列表,其中列表中的每个索引 x 包含另一个长度为 x 的单词对象列表。例如。在 results[3] 中有一个长度为 3 的对象列表,其中一个对象可能是 (dog, gdo, 3)。我有一个名为 maxL 的值,它表示列表结果 [] 的长度。如何通过遍历 results[] 及其所有列表来访问(然后打印)我想要的属性?

这是我目前所拥有的,但我知道语法是错误的:

for x in range(0,maxL):
    for y in results[x]:
        print(results[x][y].azWord)

【问题讨论】:

    标签: python list


    【解决方案1】:

    你为什么不像这样迭代列表:

    for row in results:
        for item in row:
            print(item.azWord)
    

    因为在您的示例中 results[x][y] 不正确。 y 是一个对象,而不是 int,因此您不能使用它从 results 索引。我只会使用上面的代码来拉取对象本身。

    或者使用更接近原始代码的东西

    for x in range(0,maxL):
        for y in results[x]:
            print(y.azWord) # note y is the object itself, not an index
    

    【讨论】:

    • 这似乎行得通。结果,我现在知道我的算法正在做一些有趣的事情......谢谢。
    【解决方案2】:

    在第一个循环中:

    for x in range(0,maxL):
    

    您正在遍历索引。在第二个:

    for y in results[x]:
    

    你正在循环元素。在这种情况下,通过列表的元素。所以你可以像这样访问属性:

    print(y.azWord)
    # ...
    

    注意:

    • 我建议您关注Python naming conventions。将您的班级命名为Word

    • 我还建议您使用更具代表性的名称,例如:

      for i in range(0, maxL):
          for element in results[i]:
              print(element.azWord)
      
    • 您还可以在第一个循环中循环遍历元素。除非您想修改元素或需要使用索引,否则您应该这样做:

      for words_list in results:
          for word in words_list:
              print(word.azWord)
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 2012-11-12
      相关资源
      最近更新 更多