Merlin
Merlin

Reputation: 25639

How to change string to Integers in python

Trying to remove single quotes from around numbers. I'm working with third paty data that's not well typed.

lst =  [ ('text','2','3','4'), ('text2','4','5','6') ]
y=  [map(int,i) for i in zip(*lst)[1:]] 

d = zip(*list)[0]
print d
c= zip(*y)
print c

dd = zip(d,c)
print dd

this is what the out is:

('text', 'text2')
[(2, 3, 4), (4, 5, 6)]
[('text', (2, 3, 4)), ('text2', (4, 5, 6))]

How Do I get:

dd =  [ ('text',2,3,4), ('text2',4,5,6) ]

EDIT: If list is sometimes this: [ ['text','2','3','4'], ['text2','4','5','6'] ], then what do i do? Another problem is integer as '3,400'.

New Lst example:

  lst =  [ ('text','2','3','4'), ('text2','4','5,000','6,500') ]

Need:

 [ ('text',2,3,4), ('text2',4,5000,6500) ]

Upvotes: 0

Views: 464

Answers (4)

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143144

Jochen's answer is the right thing for your specific case.

If, for some reason, you need to take the list of types as a parameter you can do something like this:

>>> lst =  [ ('text','2','3','4'), ('text2','4','5','6') ]

>>> def map_rows(types, rows):
...     return [tuple(f(x) for f, x in zip(types, row)) for row in rows]

>>> map_rows((str, int, int, int), lst)
[('text', 2, 3, 4), ('text2', 4, 5, 6)]

The map_rows defined above is sort of a cousin of the standard map function. Note that "types" is really a sequence of callables that "convert" the value in whatever way you want.

Upvotes: 2

Asterisk
Asterisk

Reputation: 3574


lst =  [ ('text','2','3','4'), ('text2','4','5','6') ]

new_lst = []

for tup in lst:
    tmp = []
    for index, item in enumerate(tup):
        if index != 0:
            tmp.append(int(item))
        else:
            tmp.append(item)
    new_lst.append(tuple(tmp))

print new_lst

This is probably not the pythonic way of doing it :)

Upvotes: 0

Artur Gaspar
Artur Gaspar

Reputation: 4552

lst = [('text','2','3','4'), ('text2','4','5','6')]
dd = []
for t in lst:
    new_tuple = []
    for i in t:
        try:
            new_tuple.append(int(i))
        except ValueError:
            new_tuple.append(i)
    dd.append(tuple(new_tuple))

Upvotes: 1

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

print [(text, int(a), int(b), int(c)) for (text, a, b, c) in lst]

Upvotes: 8

Related Questions