Python:打印所有命名元组

标签 python namedtuple

我有以下代码:

from collections import namedtuple

Test = namedtuple('Test', ['number_A', 'number_B'])

test_1 = Test(number_A=1, number_B=2)
test_2 = Test(number_A=3, number_B=4)
test_3 = Test(number_A=5, number_B=6)

我的问题是如何打印所有命名元组,例如:

print (Test.number_A)

我希望看到这样的结果:

1
3
5

有什么想法吗? 谢谢..

最佳答案

Martijn Peters 在评论中提出建议:

Do not use numbered variables. Use a list to store all the named tuples instead. Simply loop over the list to print all contained named tuples.

这是它的样子:

Test = namedtuple('Test', ['number_A', 'number_B'])
tests = []
tests.append(Test(number_A=1, number_B=2))
tests.append(Test(number_A=3, number_B=4))
tests.append(Test(number_A=5, number_B=6))

for test in tests:
    print test.number_A

给予:

1
3
5

关于Python:打印所有命名元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18451062/

相关文章:

python - Azure 容器实例 Python API - 无法从 Azure 容器注册表获取图像

python - 在 namedtuple 中使用 '_' 作为 typename 有什么特别之处吗?

python - 我怎样才能从 Python 的 namedtuple 获得降序的 OrderedDict?

python - 直接从 typing.NamedTuple 继承时出现奇怪的 MRO 结果

python - Unpickle具有向后兼容性的namedtuple(忽略附加属性)

python - Numpy:为什么 numpy.array([2]).any() > 1 False?

python - 错误 : The truth value of a Series is ambiguous - Python pandas

python - 为什么在部署我在本地运行良好的 Flask 应用程序时,Heroku 崩溃了(代码=H10)?

python - 从文本文件加载多个图像