I have 10 lists with four elements each seperated by tabs within a large list. How do I remove the tabs, have the elements seperated within their respective lists, all within in a large list?
-
1tabs? Could you post your code please. – eat_a_lemon Mar 22 '11 at 06:04
4 Answers
Courtesy of this question. This may work.
>>> tabbedlist = 'element0\telement1\telement2\telement3'
>>> list = tabbedlist.split('\t')
>>> list
['element0', 'element1', 'element2', 'element3']
This appears to also work for: tabbedlist = 'element0 element1 element2 element3'
Where those spaces are actually tabs or at least my terminals rendering of them as spaces. (posting condenses the spaces, sorry)
So for your app:
tenlists = [
'l0e0\tl0e1\tl0e2',
'l1e0\tl1e2\tl1e3\tl1e4',
'l2e0\tl2e2',
'l3e0\tl3e2\tl3e3\tl3e4\tl3e5',
'l4e0\tl4e2\tl4e3\tl4e4\tl4e5\tl4e6',
'l5e0\tl5e2\tl5e3\tl5e4\tl5e5\tl5e6\tl5e7',
]
largelist = []
for list in tenlists:
largelist.append( list.split('\t') )
print largelist
To split a single list, use a list comprehension:
[x.split("\t") for x in list_with_tabbed_elements]
Now, you need to do this for each element of your list of lists. You could use another list comprehensions, but personally I don't like nested list comprehensions, so I'd suggest to use map here:
map(lambda l: [x.split('\t') for x in l], list_of_lists)

- 3,667
- 16
- 29
It's not clear exactly what your original data looks like from the question as it is, but perhaps this is all that you're looking for?
data = ["alpha\tbravo\tcharlie\tdelta",
"one\ttwo\tthree\tfour"]
new_data = map(lambda x: x.split("\t"), data)
print new_data
... which produced the output:
[['alpha', 'bravo', 'charlie', 'delta'], ['one', 'two', 'three', 'four']]

- 446,582
- 72
- 411
- 327
I did not understand the question fully, so I am going to make following assumptions. Please let me know if they are correct.
Your input is of the form :
a = [["test\tinput"], ["test1\tinput1"]] # 10 elements.
Following code will create a list ['test', 'input', 'test1', 'input1']
reduce(lambda x,y: x+y, [x[0].split('\t') for x in a])

- 9,597
- 1
- 20
- 25
-
I guess he want to have `[['test', 'input'], ['test1','input1']]` as a result: "have the elements seperated within their respective lists" – Lars Noschinski Mar 22 '11 at 06:09