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

Thursday, May 3, 2012

Extracting tuples or lists into named variables

This is a nice showcase showing the power of tuple extraction. If we know upfront how many fields the list or tuple will contain we can extract all individual fields into named variables. If you really want to work with CSV files there is a standard python CSV module.
#FirstName LastName Sex(0 = Male) Age
csvfile = """Robby     Pelssers   0    35
Valerie   Pelssers   1    5
Lindsey   Pelssers   1    9"""


for line in csvfile.split('\n'):
    #tuple extraction
    fName, lName, sex, age = line.split() 
    print fName + ' is ' + age + ' years old'

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

No comments:

Post a Comment