Home > database >  Python how to apply map function on elements of list if possible?
Python how to apply map function on elements of list if possible?

Time:02-01

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.

CodePudding user response:

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]

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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))
  •  Tags:  
  • Related