[Tutor] Splitting lists with strings and integers

Alan Gauld alan.gauld at btinternet.com
Wed Nov 27 02:09:27 CET 2013


On 26/11/13 19:00, Sam Lalonde wrote:

>  >>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6']
>  >>> list2 = []
>  >>> for animal in list1:
> ...     animal = animal.split()
> ...     list2.append(animal)
> ...

This could be a list comprehension:

list2 = [animal.split() for animal in list1]


>  >>> print list2
> [['dog', '1', '2'], ['cat', '3', '4'], ['mouse', '5', '6']]
>  >>>
>  >>> for animal in list2:
> ...     print animal[1] + animal[2]
> ...
> 12
>
> You can see that it just appended the numbers to each other.  I'd like
> the output to be:
>
> 3
>
> Is there a clean way to get the numbers stored as int instead of str
> when I build list2?

Define "clean".
You can use int() on the last two in a second comprehension:

list2 = [ [type, int(x), int(y)] for type,x,y in list2 ]

Or you could just wait to the point of use...

for animal in list2:
    print int(animal[1]) + int(animal[2])

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list