user506710
user506710

Reputation:

Extract integer from a list

I have a list like ['-1', '1,2,3', '2'] and I want to extract all the integers in it. I don't know the number of integers in each position of the list ie the list can also be ['2,3,4','1,2,3','-1'] but it will never have an empty string. So I want that the answer should be [2,3,4,1,2,3,-1]

What is the best way to do so in terms of complexity as well as less code.

Thanks...

Upvotes: 2

Views: 4866

Answers (4)

eyquem
eyquem

Reputation: 27575

Not the same. Test gives the truth. In THIS case, map() is faster than a list comprehension.

from time import clock
from random import randint

li = [ ', '.join([str(randint(-30,30)) for i in xrange(randint(1,8))])
       for j in xrange(1000) ]

A,B = [],[]

for fois in xrange(20):
    te = clock()
    res1 = map(int, ','.join(li).split(','))
    A.append( clock()-te )

    te = clock()
    new_list = [ int(i) for i in ','.join(li).split(',') ]
    B.append( clock()-te )

print '{:.1%}.'.format(min(B)/min(A))

a result: 115.1%. not a big one, but there is a difference

Upvotes: 0

kevpie
kevpie

Reputation: 26098

And another list comprehension.

>>> l = ['-1', '1,2,3', '2']
>>> [ int(x) for s in l for x in s.split(',')]
[-1, 1, 2, 3, 2]

Upvotes: 0

amillerrhodes
amillerrhodes

Reputation: 2702

Here's a ist comprehension:

new_list = [ int(i) for i in ','.join(old_list).split(',') ]

Upvotes: 0

NPE
NPE

Reputation: 500367

map(int, ','.join(l).split(','))

where l is your list.

Upvotes: 3

Related Questions