Reputation: 53
I have a list with items like:
['1 Paris-SG 42 20 13 3 4 +33',
'2 Lille 42 20 12 6 2 +20',
'3 Lyon 40 20 11 7 2 +20',
'4 Monaco 36 20 11 3 6 +10']
and I want to split the string in above list to get the list of lists like:
[['1', 'Paris-SG', '42 20 13 3 4 +33'],
['2', 'Lille', '42 20 12 6 2 +20'],
['3', 'Lyon', '40 20 11 7 2 +20'],
['4', 'Monaco', '36 20 11 3 6 +10']]
Here's the code I tried, but I am not getting the desired result:
ligu1 = []
for i in (final):
print(i)
for elem in sorted(i):
stat = ','.join(map(str, elem))
ligu1.append(stat)
ligu1
which gives me:
['1, ,P,a,r,i,s,-,S,G, ,4,2, ,2,0, ,1,3, ,3, ,4, ,+,3,3',
'2, ,L,i,l,l,e, ,4,2, ,2,0, ,1,2, ,6, ,2, ,+,2,0',
'3, ,L,y,o,n, ,4,0, ,2,0, ,1,1, ,7, ,2, ,+,2,0',
'4, ,M,o,n,a,c,o, ,3,6, ,2,0, ,1,1, ,3, ,6, ,+,1,0']
Upvotes: 1
Views: 73
Reputation: 83
This is the most simple way I could think it to make clear and easy to understand:
lista = ['1 Paris-SG 42 20 13 3 4 +33',
'2 Lille 42 20 12 6 2 +20',
'3 Lyon 40 20 11 7 2 +20',
'4 Monaco 36 20 11 3 6 +10']
string =[]
number = []
for i in lista:
string.append(i.split(" "))
arr = []
for i in range(len(string)):
temp = ''
arr.append(string[i][:2])
for j in string[i][3:]:
temp +=j
arr[i].append(temp)
print(arr)
Upvotes: 0
Reputation: 48090
You can write list comprehension using str.split()
with maxsplit
param as 2 to achieve this:
my_list = [
'1 Paris-SG 42 20 13 3 4 +33',
'2 Lille 42 20 12 6 2 +20',
'3 Lyon 40 20 11 7 2 +20',
'4 Monaco 36 20 11 3 6 +10'
]
new_list = [s.split(' ', 2) for s in my_list]
where new_list
will hold:
[
['1', 'Paris-SG', '42 20 13 3 4 +33'],
['2', 'Lille', '42 20 12 6 2 +20'],
['3', 'Lyon', '40 20 11 7 2 +20'],
['4', 'Monaco', '36 20 11 3 6 +10']
]
Upvotes: 5