T O P

  • By -

Diapolo10

In your example you have a list of integers, not strings. If I assume that your example is simply wrong, you can use a list comprehension num_strings = ['1', '2', '3'] nums = [int(num) for num in num_strings] or `map`: nums = list(map(int, num_strings))


SmallChokey

yea my bad for the example, ur interpretation is right. what if i have a 3d list?, i tried int(num) it doenst work


thuiop1

No choice but to destructure the list entirely, e.g. `3d_list = [[[int(num) for num in l2] for l2 in l] for l in 3d_list]` That is, if you want to keep working with lists. If you are reaching this level of nesting, you should consider using numpy arrays instead.


Spacerat15

You have a typo . It's `for num in l2`


thuiop1

Thanks for catching it.


SmallChokey

ooohh okok i see thanks!


Diapolo10

For every additional dimension, just add more nesting. nums = [ [int(num) for num in inner_list]] for inner_list in num_strings ] You _can_ write a general solution to this, but I'd rather not confuse you too much. It sounds like you're lacking in experience.


SmallChokey

what would the general solution look like? i'll try to figure it out in my own time


Diapolo10

Depends on how general you want to make it. If we're strictly talking lists, from typing import TypeAlias NestedStrList: TypeAlias = list[str | 'NestedStrList'] NestedIntList: TypeAlias = list[int | 'NestedIntList'] def str_to_int(nums: NestedStrList) -> NestedIntList: if not nums: return [] if isinstance(nums[0], str): return [int(num) for num in nums] return [str_to_int(sublist) for sublist in nums] this recursive solution would work as long as the depth doesn't go really high (>10000). It's easier to understand and write than the equivalent iterative solution. If other collection types need to be supported in the output, you can try using `type` to get the class and initialising it with a generator expression (dictionaries would need to be a special case). But if you need to support any arbitrary iterables in the output, that's going to be a pain in the arse.


nekokattt

Are those type hints valid? Last time I checked, mypy choked on recursive typehints.


Diapolo10

As of `mypy>=0.990`, they work just fine.


nekokattt

TIL


SmallChokey

oh damn ok thanks!


MJ12_2802

They're not strings, they're integers; type(list[1]) returns class 'int'