Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

python - How to convert list of intable strings to int

In Python, I want to convert a list of strings:

l = ['sam','1','dad','21']

and convert the integers to integer types like this:

t = ['sam',1,'dad',21]

I tried:

t = [map(int, x) for x in l]

but is showing an error.

How could I convert all intable strings in a list to int, leaving other elements as strings?

My list might be multi-dimensional. A method which works for a generic list would be preferable:

l=[['aa','2'],['bb','3']]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd use a custom function:

def try_int(x):
    try:
        return int(x)
    except ValueError:
        return x

Example:

>>> [try_int(x) for x in  ['sam', '1', 'dad', '21']]
['sam', 1, 'dad', 21]

Edit: If you need to apply the above to a list of lists, why didn't you converted those strings to int while building the nested list?

Anyway, if you need to, it's just a matter of choice on how to iterate over such nested list and apply the method above.

One way for doing that, might be:

>>> list_of_lists = [['aa', '2'], ['bb', '3']]
>>> [[try_int(x) for x in lst] for lst in list_of_lists]
[['aa', 2], ['bb', 3]]

You can obviusly reassign that to list_of_lists:

>>> list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...