[Tutor] Splitting lists with strings and integers

Dominik George nik at naturalnet.de
Wed Nov 27 01:57:38 CET 2013


Hi,

> 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.

First, let's do it with a list comprehension. You should really learn those if you do serious Python programming ;)!

   list2 = [[int(z) if z.isdigit() else z for z in y] for y in [x.split(" ") for x in list1]]

Now, to convert every possible numeric string in a list to int in a more
readable fashion:

   for x in xrange(len(animal)):
       if animal[x].isdigit():
           animal[x] = int(animal[x])

So:

 - the isdigit() method of a string tells you if it is numeric
 - int() casts to an integer

The list comprehension does the whole converion with list
comprehensions. You should consider readability when doing such things,
but you should learn it.

-nik           

-- 
# apt-assassinate --help
Usage: apt-assassinate [upstream|maintainer] <package>

PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17  FD26 B79A 3C16 A0C4 F296
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 905 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/tutor/attachments/20131127/a86ccbb9/attachment.sig>


More information about the Tutor mailing list