[Tutor] Splitting lists with strings and integers

Amit Saha amitsaha.in at gmail.com
Wed Nov 27 02:00:23 CET 2013


On Wed, Nov 27, 2013 at 5:00 AM, Sam Lalonde <sl70176 at gmail.com> wrote:
> Hi, I am very new to python.
>
> I have a list with mixed strings/integers.  I want to convert this to a list
> of lists, and I want the numbers to get stored as integers.
>
>>>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6']
>>>> list2 = []
>>>> for animal in list1:
> ...     animal = animal.split()
> ...     list2.append(animal)
> ...
>>>> print list2
> [['dog', '1', '2'], ['cat', '3', '4'], ['mouse', '5', '6']]
>>>>
>>>> for animal in list2:
> ...     print animal[1] + animal[2]
> ...
> 12
> 34
> 56

The numbers are appended because:

'1' + '2' = '12' and so on.

>
> You can see that it just appended the numbers to each other.  I'd like the
> output to be:
>
> 3
> 7
> 11
>
> Is there a clean way to get the numbers stored as int instead of str when I
> build list2?

Consider your original list:

>>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6']


For each item of the list, you want to extract the numbers and add
them with the sums in a new list. Let's take it one step at a time

>>> # extract the numbers only
... for item in list1:
...     print item.split()[1:]
...
['1', '2']
['3', '4']
['5', '6']

But, we want each number as integer and print their sum instead of the
individual numbers:

>>> for item in list1:
...     print int(item.split()[1]) + int(item.split()[2])
...
3
7
11


So, we have our numbers. But we would like this to be a list instead.
So, instead of printing, simply create a list.

Hope that helps.

Best,
Amit.




>
> Thanks
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
http://echorand.me


More information about the Tutor mailing list