Reputation: 89
I have a list:
lines = [['1 1 4.59114 0.366832 -9.56424 '], ['2 1 5.24742 -0.870574 -8.40649 '], ['3 2 5.21995 -0.38856 -7.39145 ']]
I want to split each individual element of the list as follows:
[['1', '1 4.59114', '0.366832', '-9.56424'], ['2', '1', '5.24742', '-0.870574', '-8.40649 '], ['3', '2', '5.21995', '-0.38856', '-7.39145']]
I tried the following code:
m = []
for i in range(len(lines)):
a = re.split(r'\t+', lines[i].rstrip('\t').split(",")
m.append(a)
However split doesn't work on individual list elements. Any ideas?
Upvotes: 1
Views: 5312
Reputation: 362
Try this :
print([list[0].split() for list in lines])
output :
[['1', '1', '4.59114', '0.366832', '-9.56424'], ['2', '1', '5.24742', '-0.870574', '-8.40649'], ['3', '2', '5.21995', '-0.38856', '-7.39145']]
Upvotes: 1
Reputation: 353
It is a list of list of strings.
lines[0][0].split(' ') # lines[0][0] is a string so you can use split
will give you ['1', '1', '4.59114', '0.366832', '-9.56424', '']
You can do
[x[0].split(' ') for x in lines]
to get the desired result.
Upvotes: 1
Reputation: 19801
You need to split
on the whitespace character and not on the tab \t
:
>>> lines = [['1 1 4.59114 0.366832 -9.56424 '], ['2 1 5.24742 -0.870574 -8.40649 '], ['3 2 5.21995 -0.38856 -7.39145 ']]
>>> [line[0].split() for line in lines]
[['1', '1', '4.59114', '0.366832', '-9.56424'],
['2', '1', '5.24742', '-0.870574', '-8.40649'],
['3', '2', '5.21995', '-0.38856', '-7.39145']]
Upvotes: 5