Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获取要打印的标题_Python - Fatal编程技术网

Python 如何获取要打印的标题

Python 如何获取要打印的标题,python,Python,如果我们获得此代码: from collections import namedtuple Book = namedtuple('Book', 'title author year price') favorite = Book('Adventures of Sherlock Holmes', 'Arthur Conan Doyle', 1892, 21.50) another = Book('Memoirs of Sherlock Holmes',

如果我们获得此代码:

from collections import namedtuple
Book = namedtuple('Book', 'title author year price')
favorite = Book('Adventures of Sherlock Holmes',
                'Arthur Conan Doyle', 1892, 21.50)
another = Book('Memoirs of Sherlock Holmes', 
               'Arthur Conan Doyle', 1894, 23.50)
still_another = Book('Return of Sherlock Holmes',
                     'Arthur Conan Doyle', 1905, 25.00)
如何在变量中获得要打印的书名

您可以执行以下操作:

print(still_another.title)
namedtuple
中的每个值都可以通过其名称访问,在您的情况下,可以通过
访问标题。标题可以执行以下操作:

print(still_another.title)

namedtuple
中的每个值都可以通过其名称进行访问,在您的案例中,标题可以通过
进行访问。同样地
还有另一个[0]
,因为标题恰好是首先定义的。为完整起见,NamedTuples支持整数索引,尽管属性访问(如本答案中所示)通常更清晰,并且更符合您的要求。同样地,
仍然\u另一个[0]
,因为标题恰好是首先定义的。为了完整性,NamedTuples支持整数索引,尽管属性访问(如本答案中所示)通常更清晰,并且更符合您的需要。