By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,035 Members | 1,995 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,035 IT Pros & Developers. It's quick & easy.

how to parse a tab delimited text file into separate lists

P: 1
I have a list ['Name\tAge\n', 'Mark\t32\n', 'Matt\t29\n', 'John\t67\n', 'Jason\t45\n', 'Matt\t12\n', 'Frank\t11\n', 'Frank\t34\n', 'Frank\t65\n', 'Frank\t78\n'] that was read from a tab delimited text file.

It has a header (Name and Age) and is in two columns in the text file before import. I would like to parse the two "columns" into separate lists or strings (the Names and the Ages) so that I can, for example, calculate the average ages of the individuals. I have tried a number of different ways to do this, but cant seem to figure it out.

Any suggestions?
Sep 30 '11 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 2.5K+
P: 2,851
Here's one way:
Expand|Select|Wrap|Line Numbers
  1. >>> data = ['Name\tAge\n', 'Mark\t32\n', 'Matt\t29\n', 'John\t67\n', 'Jason\t45\n', 'Matt\t12\n', 'Frank\t11\n', 'Frank\t34\n', 'Frank\t65\n', 'Frank\t78\n']
  2. >>> names = []
  3. >>> ages = []
  4. >>> for item in data[1:]:
  5. ...     name, age = item.strip().split("\t")
  6. ...     names.append(name)
  7. ...     ages.append(age)
  8. ...     
  9. >>> names
  10. ['Mark', 'Matt', 'John', 'Jason', 'Matt', 'Frank', 'Frank', 'Frank', 'Frank']
  11. >>> ages
  12. ['32', '29', '67', '45', '12', '11', '34', '65', '78']
Sep 30 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.