0

I have a list

a=['10,20,30','30,45,90','40,56,80']

each element of the list is a string. I want to make a list of lists, such that it will look like this:

a=[[10,20,30],[30,45,90],[40,56,80]]

Any ideas? Thanks

2 Answers 2

2

.split splits the string into strings, so we'll convert each one to int after splitting.

>>> a = ['10,20,30','30,45,90','40,56,80']
>>> [[int(y) for y in x.split(',')] for x in a]
[[10, 20, 30], [30, 45, 90], [40, 56, 80]]
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it using split as follows:

b = [map(int, i.split(',')) for i in a]

>>> print b
[[10,20,30],[30,45,90],[40,56,80]]

The split method splits the string on the specified sub-string, in this case: ','. A split without any arguments, such as string.split() will split the string on a whitespace character and then return a list.

2 Comments

your code will produce list of strings not numbers [['10', '20', '30'], ['30', '45', '90'], ['40', '56', '80']]
@vaibhaw, Thank you. I have updated my answer. It gives ints now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.