简体   繁体   中英

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) ]
print [(text, int(a), int(b), int(c)) for (text, a, b, c) in lst]

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.

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

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM