Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Wednesday, May 9, 2012

Using Python named tuples to write understandable code

Remember that we were able to extract a tuple into named variables? This was a pretty neat trick. But Python even allows us to create some class alike tuples whose values can be accessed either by index or name.
import collections    
Person = collections.namedtuple('Person','firstname lastname sex age')

#FirstName LastName Sex(0 = Male) Age
csvfile = """Robby     Pelssers   0    35
Valerie   Pelssers   1    5
Lindsey   Pelssers   1    9"""

persons = map(Person._make, (line.split() for line in csvfile.split('\n')))

for person in persons:
    print person.firstname + ' ' + person.lastname + ' is ' + person[3] + ' years old.' 

Robby Pelssers is 35 years old.
Valerie Pelssers is 5 years old.
Lindsey Pelssers is 9 years old.

No comments:

Post a Comment