【问题标题】:Print a 2d list from a class in Python?从 Python 中的类打印二维列表?
【发布时间】:2020-07-29 23:12:01
【问题描述】:
class Mobile:
    def __init__(self, model, type, year):
        self.model = model
        self.type = type
        self.year = year

mobilePhones = [
    ["Samsung", "Galaxy S8", "2000"],
    ["Samsung", "Galaxy S9", "2001"],
    ["Samsung", "Galaxy S10", "2002"],
    ["Apple", "iPhone 8", "2005"],
    ["Apple", "iPhone 10", "2006"],
    ["Apple", "iPhone 11", "2007"],
]

phones = [
    Mobile(mobilePhones[0][0],mobilePhones[0][1],mobilePhones[0][2]),
    Mobile(mobilePhones[1][0], mobilePhones[1][1], mobilePhones[1][2]),
    Mobile(mobilePhones[2][0], mobilePhones[2][1], mobilePhones[2][2]),
    Mobile(mobilePhones[3][0], mobilePhones[3][1], mobilePhones[3][2]),
    Mobile(mobilePhones[4][0], mobilePhones[4][1], mobilePhones[4][2]),
    Mobile(mobilePhones[5][0], mobilePhones[5][1], mobilePhones[5][2]),
]

print(phones.model)

我只是想知道为什么这个逻辑不起作用?我正在尝试将 2dlist 中的每个数据添加到类中,以便能够调用所有模型、类型或年份。

print(mobilePhones[0][1]) 有效,但当我尝试从课堂上调用它时无效。喜欢:

print(phones.model) or print(phones.year).

【问题讨论】:

  • 另外,省点力气:phones = [Mobile(*item) for item in mobilePhones]

标签: python arrays list class


【解决方案1】:

因为phones 是一个list 对象。 您需要通过索引/循环访问其有序的内容/对象。然后在这些内容/对象上,您可以调用它提供的可调用对象。

【讨论】:

    【解决方案2】:

    您没有尝试从具有phones.model 的类中访问它。您正在尝试从列表中访问它。您需要先选择一个索引,即phones[0].model。或者如果你想打印所有的模型,

    for phone in phones:
        print(phone.model)
    

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 2017-05-22
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多