[Tutor] Splitting lists with strings and integers
spir
denis.spir at gmail.com
Wed Nov 27 11:19:19 CET 2013
On 11/26/2013 08:00 PM, Sam Lalonde 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']
There is a little interpretation error in your terms "a list with mixed
strings/integers": list1 is a simple list of strings, meaning pieces of textual
data. Right? Ii just happens that parts of each of those strings match a
standard _notation_ of numbers (natural integers expressed in positional
indo-arabic numeral notation, for the matter).
Think at this, you could also have:
list1 = ['dog I II', 'cat III IV',...
or
list1 = ['dog uno due', 'cat tre cuatro',...
It would be textual data the same way. Number notations are pieces of text.
>>>> 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
>
> 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?
You must ask Python to _decode_ the numeric notation nested in the pieces of
strings into actual numbers, then perform numeric operations on them. Also,
before that, for a "clean way" as you say, you may isolate each numeric notation.
As a side note, an issue apparent here is that python uses the same operator
sign '+' for arithmetic sum and string (con)catenation. (Not all language share
this choice, it is a language design point.) Else, you would get a Type Error
saying than one cannot add pieces of text.
You can get an answer to this question in the Python programming FAQ at
[http://docs.python.org/2/faq/programming.html#is-there-a-scanf-or-sscanf-equivalent]
(scanf is the C function that does what you need).
Also
[http://docs.python.org/2/faq/programming.html#how-do-i-convert-a-string-to-a-number].
> Thanks
Denis
More information about the Tutor
mailing list