views:

84

answers:

3

I have a list of elements, and each element consists of four seperate values that are seperated by tabs:

['A\tB\tC\tD', 'Q\tW\tE\tR', etc.]

What I want is to create a larger list without the tabs, so that each value is a seperate element:

['A', 'B', 'C', 'D', 'Q', 'W', 'E', 'R', etc.]

How can I do that in Python? I need it for my coursework, due tonight (midnight GMT) and I'm completely stumped.

+5  A: 

All at once:

'\t'.join(['A\tB\tC\tD', 'Q\tW\tE\tR']).split('\t')

One at a time:

[c for s in ['A\tB\tC\tD', 'Q\tW\tE\tR'] for c in s.split('\t')]

Or if all elements are single letters:

[c for s in ['A\tB\tC\tD', 'Q\tW\tE\tR'] for c in s[::2]]

If there could be quoted tabs then:

import csv
rows = csv.reader(['A\t"\t"\tB\tC\tD', 'Q\tW\tE\tR'], delimiter='\t')
[c for s in rows for c in s] # or list(itertools.chain.from_iterable(rows))
J.F. Sebastian
A: 

Homework question?

t = ['A\tB\tC\tD', 'Q\tW\tE\tR']
sum((x.split('\t') for x in t),[])
Noufal Ibrahim
Thank you guys so much, this is a massive help :D
Trivun
A: 

This should work:

t = ['A\tB\tC\tD', 'Q\tW\tE\tR']

t = reduce(lambda x, y: x + y, map(str.split,t))
Sean Nilan
Use `sum(map(str.split, t), [])` if you are going that route.
J.F. Sebastian