1

so if i have like 100 sublists in have to replace strings into integer L = ['2013', 'Patrick', 'M', '2566']

I must convert 2013 and such numbers into integer for all the sublists. I tried: Assume 4 elements per sublist newlist = [map(int,x) for x in L[0][:5]]

but obviously I keep getting error because 'patrick' cannot be converted.

3 Answers 3

5

you can you simple list comprehension :)

results = [int(i) if i.isdigit() else i for i in L]
Sign up to request clarification or add additional context in comments.

Comments

2

Another option is to catch ValueError and fallback to original value, if more flexibility is needed than one-liner provides:

L = ['2013', 'Patrick', 'M', '2566']

def try_convert(string):
    try:
        return int(string)
    except ValueError:
        return string

newlist = map(try_convert, L)

Results in:

[2013, 'Patrick', 'M', 2566]

Comments

0

Try this, iterate your main list, and rebuilt sublists converting to int depending on isdigit() function:

>>> #your main list    
>>> huge_list = [
...     ['2013', 'Patrick', 'M', '2566'],
...     ['1', 'Bob', 'M', '25']
... ]
>>> #for each sublist, convert only the elements that are numbers (using isdigit() function)
>>> for idx, sublist in enumerate(huge_list):
...     huge_list[idx] = [
...         int(el) if el.isdigit() else el
...         for el in sublist
...     ]
... 
>>> huge_list
[[2013, 'Patrick', 'M', 2566], [1, 'Bob', 'M', 25]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.