How can I turn a single element in a list into multiple elements using Python?
I have a list of elements, and each element consists of four separate values that are separated by tabs:
['A\tB\tC\tD', 'Q\tW\tE\tR', etc.]
What I wan开发者_如何学运维t is to create a larger list without the tabs, so that each value is a separate 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.
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))
Homework question?
t = ['A\tB\tC\tD', 'Q\tW\tE\tR']
sum((x.split('\t') for x in t),[])
This should work:
t = ['A\tB\tC\tD', 'Q\tW\tE\tR']
t = reduce(lambda x, y: x + y, map(str.split,t))
精彩评论