Is it possible to create a tuple in Python with indices that are string-based, not number based? That is, if I have a tuple of ("yellow", "fish", "10)
, I would be able to access by [color]
instead of [0]
. This is really only for the sake of convenience.
You can use collections.namedtuple()
:
>>> from collections import namedtuple
>>> MyObject = namedtuple('MyObject', 'color number')
>>> my_obj = MyObject(color="yellow", number=10)
>>> my_obj.color
'yellow'
>>> my_obj.number
10
And you can still access items by index:
>>> my_obj[0]
'yellow'
>>> my_obj[1]
10
是的,尽管您将使用x.color
而不是x['color']
访问颜色,但collections.namedtuple
执行此操作
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.