2

Let's say I have a list like so:

a = ['abc1', '2def', 'g3h']

And I am trying to make it like this using list comprehension:

['abc', 'def', 'gh']

What I've tried:

[''.join([x for y in a for x in y if x.isalpha()])]

Which produces:

# ['abcdefgh']

Is there a neat way of achieving ['abc', 'def', 'gh'] using list comprehension?

1
  • [re.sub('\d+', '', _) for _ in a] and import re Commented Jan 11, 2021 at 18:42

3 Answers 3

2

Using str.join in a nested comprehension

Ex:

a = ['abc1', '2def', 'g3h']
print(["".join(j for j in i if j.isalpha()) for i in a])
# -> ['abc', 'def', 'gh']
Sign up to request clarification or add additional context in comments.

3 Comments

Or use not j.isdigit() or not j.isnumeric() if the goal is just to exclude numeric characters, not keep solely alphabetic characters.
@ShadowRanger, do you think using not isnumeric() would be faster than isalpha()? Would this have something to do with the differences in items that need to be checked? I mean there are more letters than numbers.
@JonasPalačionis: I wouldn't worry about the speed here; do what's correct (do you want to blacklist numeric stuff? Whitelist alphabetic characters? If there is a whitespace character, do you keep it or not?). Odds are, you won't notice any difference in speed either way; interpreter overhead is likely to swamp the tiny differences. And fastest to the wrong answer is still wrong.
1

If you can use regex, I would go for this:

import re
a = ['abc1', '2def', 'g3h']
[re.sub("\d+", "", x) for x in a]

1 Comment

Thanks for the regex approach!
0

Use of map and filter

list(map(lambda x:"".join(filter(lambda y:y.isalpha(), x))  ,a))

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.