如何在每次向列表添加新项时创建新对象

2024-09-29 21:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这样一个问题:

array_of_things = [[is_shiny=False, is_bumpy=True]
                   [is_shiny=False, is_bumpy=False]
                   [is_shiny=True, is_bumpy=True]]

要访问项目,我将执行以下操作:

if array_of_things[1][1] == True: #If the second item in list is bumpy
    print("The second item is bumpy")

但是,为了使我的代码更清晰,我希望数组中的每个项都可以像这样访问:

if array_of_things[1].is_bumpy == True: #If the second item in the list is bumpy
    print("The second item is bumpy")

我该怎么做?任何帮助都将不胜感激


Tags: oftheinfalsetrueifisitem
2条回答

一个选项是使用dict,但如果您想确切地使用问题中给出的语法^{},可以使用:

from collections import namedtuple

Thing = namedtuple('Thing', ['is_shiny', 'is_bumpy'])
array_of_things = [Thing(False, True), Thing(False, False), Thing(True, True)]

if array_of_things[1].is_bumpy == True:
    print("The second item is bumpy")

namedtuple创建一个新的tuple子类,其类型名为第一个参数。可以使用与普通tuple一样的索引访问字段,也可以使用在第二个参数中传递的字段名访问字段

如果这些“东西”对您的程序有重要意义,我建议您定义一个类,否则,请使用dicts:

array_of_things = [{'is_shiny': False, 'is_bumpy': True},
                   {'is_shiny': False, 'is_bumpy': False},
                   {'is_shiny': True, 'is_bumpy': True}]

if array_of_things[1]['is_bumpy']:  # since it's a boolean, no need for `==`
    print("The second item is bumpy")

相关问题 更多 >

    热门问题