Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Print all namedtuples

I have the following code:

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)

My question is how can I print all namedtuples, for example:

print (Test.number_A)

I want to see somthing like this as a result:

1
3
5

any ideas? thanks..

like image 734
user2719106 Avatar asked Jul 22 '26 07:07

user2719106


2 Answers

Martijn Peters advises in the comments:

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.

Here is what that looks like:

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

Gives:

1
3
5
like image 148
Steven Rumbalski Avatar answered Jul 23 '26 21:07

Steven Rumbalski


You could drive a subclass that kept track of its instances:

from collections import namedtuple

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

class Test(_Test):
    _instances = []
    def __init__(self, *args, **kwargs):
        self._instances.append(self)
    def __del__(self):
        self._instances.remove(self)
    @classmethod
    def all_instances(cls, attribute):
        for inst in cls._instances:
            yield getattr(inst, attribute)

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)

for value in Test.all_instances('number_A'):
    print value

Output:

1
3
5
like image 36
martineau Avatar answered Jul 23 '26 23:07

martineau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!