2

I have a situation where I am using list comprehension to scan one list and return items that match a certain criteria.

[item for item in some_list_of_objects if 'thisstring' in item.id]

I want to expand this and have a list of things that can be in the item, the list being of unknown length. Something like this:

string_list = ['somestring', 'another_string', 'etc']

[item for item in some_list_of_objects if one of string_list in item.id]

What is a pythonic way to accomplish this? I know I could easily rewrite it to use the standard loop structure, but I would like to keep the list comprehension if I can do so without producing very ugly code.

Thanks in advance.

4
  • 1
    Honestly, I think your best bet is to use a loop. It'll probably end up the cleanest in the long-run. Commented May 29, 2015 at 20:47
  • How big is your string_list in reality? Commented May 30, 2015 at 10:08
  • @StefanPochmann probably about 30. I'm breaking a DNA string into codons then doing translation. Commented May 30, 2015 at 18:58
  • Yeah, I'm going to solve this with a standard loop, it's not that hard, and much cleaner. Commented Jun 5, 2015 at 20:45

2 Answers 2

2

Use any:

string_list = ['somestring', 'another_string', 'etc']

[item for item in some_list if any(s in item.id for s in string_list)]

any will lazily evaluate breaking on the first match or checking all if we don't get a match.

Sign up to request clarification or add additional context in comments.

4 Comments

@AdamSmith, was my first thought but the OP wants to match also substrings based on their question, if the logic was item.id in string_list then a set would work
@PadraicCunningham oh I didn't notice he was doing substring matching. I should read the question closer!
Yeah, I guess I should have clarified in my question. I'm working with DNA strings and I need to map codons to amino acids via a table of values.
Do you have a lot of data to process?
2

You can use the builtin any function for that [item for item in some_list if any(s in item for s in string)]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.