Mpizos Dimitris
Mpizos Dimitris

Reputation: 4991

Optimizing by using list comprehension

Lets say I have the following list:

StringLists = ['1,8,0,9','4,5,2,2','4,6,7,2','4,2,8,9']

And I want to generate the following result:

FinalList = [[1,8,0,9],[4,5,2,2],[4,6,7,2],[4,2,8,9]]

I am using the following code:

TempList = [d.split(',') for d in StringLists]
FinalList = list()
for alist in TempList:
    FinalList.append([int(s) for s in alist])

The result is ok, but i was wondering if there is something more elegant. Any idea?

Upvotes: 1

Views: 65

Answers (4)

Delgan
Delgan

Reputation: 19627

What about:

FinalList = [list(map(int, d.split(','))) for d in StringLists]

Note that if you are using Python 2, you do not have to cast the result:

FinalList = [map(int, d.split(',')) for d in StringLists]

Upvotes: 3

saikumarm
saikumarm

Reputation: 1575

One way to do it

>>> [[int(s) for s in string.split(',')] for string in StringLists]
[[1, 8, 0, 9], [4, 5, 2, 2], [4, 6, 7, 2], [4, 2, 8, 9]]

Upvotes: 3

JuniorCompressor
JuniorCompressor

Reputation: 20015

You can use:

StringLists = ['1,8,0,9','4,5,2,2','4,6,7,2','4,2,8,9']
print map(lambda s: map(int, s.split(',')), StringLists)

Output:

[[1, 8, 0, 9], [4, 5, 2, 2], [4, 6, 7, 2], [4, 2, 8, 9]]

Upvotes: 2

Riyaz
Riyaz

Reputation: 1470

How about this:

TempList = [map(int, d.split(',')) for d in StringLists]

Upvotes: 1

Related Questions