-2

I have a list that looks like this

['111', '222', '333', 'xxx', '3233']

I'd like to change all elements to int if possible. In this case, xxx is not a digit. So how can I ignore 'xxx' and change all other elements to int?

I can do this with a for loop and some if statements. But I prefer to use map function if possible. Any other convenient way would be appreciated.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
user8314628
  • 1,952
  • 2
  • 22
  • 46

4 Answers4

8

Why map? A list comprehension is much more readable and you can't exclude items from a map (without using filter or another generator expression):

>>> mylist = ['111', '222', '333', 'xxx', '3233']
>>> [int(x) for x in mylist if x.isdigit()]
[111, 222, 333, 3233]

Note that this would only work for positive integers as - or . are not digits.

The wording in your question (ignore xxx) is a bit vague. If you wanted to keep it as a string you should use this:

>>> [int(x) if x.isdigit() else x for x in mylist]
[111, 222, 333, 'xxx', 3233]
Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

Map takes as input, a function and an iterable.

A function that would do what you want would be something like this:

def convert(input_str: str):
    try:
        return int(input_str)
    except ValueError:
        return input_str

Then you would just use it in a map call:

l = ['111', '222', '333', 'xxx', '3233']

map(convert, l)
Justin Furuness
  • 685
  • 8
  • 21
0

Simpler one line using map:

x = ['111','xxx','222']
y = map(lambda n: int(n) if n.isdecimal() else n,x)
print(list(y))

Keep in mind as Selcuk said, using list comprehension is probably better and cleanerm

Zaid Al Shattle
  • 1,454
  • 1
  • 12
  • 21
0
vals = ['111', '222', '333', 'xxx', '3233']

[int(val) if val.isdigit() else val for val in vals]
list(map(lambda val: int(val) if val.isdigit() else val, vals))
Sdq
  • 21
  • 2
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? Please see the other answers for examples. – Jeremy Caney Feb 01 '22 at 00:55