-1

I have a list: aa=["tea","tee","tea_N","tee_N"]

I want to get the elements with last two characters are "_N".

The result is like: ["tea_N","tee_N"]

How could I do this? Thanks!

Freeego
  • 135
  • 6
  • Does this answer your question? [Filter a list according to condition in Python](https://stackoverflow.com/questions/61326041/filter-a-list-according-to-condition-in-python) – Pranav Hosangadi Jan 18 '23 at 00:22

1 Answers1

1
list(filter(lambda x: x.endswith("_N"), aa))

See documentation for filter and str.endswith.

Equivalent list comprehension:

[x for x in aa if x.endswith("_N")]
Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41
  • Don't use a `filter` when all you want is a list comprehension. https://stackoverflow.com/a/3013686/843953 – Pranav Hosangadi Jan 18 '23 at 00:21
  • May I ask how to get the elements based on two conditions? For example, I want to get the elements ending with "_N" or "ee"? So I the result is ["tee,"tea_N","tee_N"] – Freeego Jan 18 '23 at 00:24
  • @Freeego You just add that check to the predicate `or x.endswith("ee")`. – Daniil Fajnberg Jan 18 '23 at 00:25
  • It was a comment to OP and other readers telling them why to prefer a list comprehension over `filter`. Don't take things so personally – Pranav Hosangadi Jan 18 '23 at 00:25
  • @PranavHosangadi Not at all. Just amusing how you simply state that as though it is the law instead of even hinting at a _reason_ or an _argument_ as to why we should use a list comprehension in place of `filter`. That post you linked is years old. Do you have recent benchmarks? – Daniil Fajnberg Jan 18 '23 at 00:26
  • The comment includes a link to an answer that goes into more detail than I could possibly hope to in a comment. There are other, more recent answers there. – Pranav Hosangadi Jan 18 '23 at 00:27
  • A quick test of your code on Py3.7.9 shows the list comprehension is 1.7x faster. I don't have access to a newer version to test, but I expect you'll see similar results – Pranav Hosangadi Jan 18 '23 at 00:32