Data Mastery
Data Mastery

Reputation: 2085

Subset list: Find only exact matches in Python

This is my list:

smalllist = ['191010.National Geographic','191010.PRO7MAXX', '191010.PRO7', "191022.PRO7MAXX", "191022.PRO7"]


list(filter(lambda x: x.find("PRO7") > -1, smalllist))

I wanted to use this method to only get the exact matches in the list. Important: I tried it also with index but this only gave me the first match. I need ALL EXACT matches of the SUBSTRING.

Output: ['191010.PRO7MAXX', '191010.PRO7', '191022.PRO7MAXX', '191022.PRO7']
Desired Output: ['191010.PRO7','191022.PRO7']

How can I this done? :/

Upvotes: 0

Views: 229

Answers (2)

SuperMouette
SuperMouette

Reputation: 345

you can also use

[element for element in smalllist if element.split('.')[1]=='PRO7']

that way, it will work even if you have something like '1245.UNPRO7'

Upvotes: 1

Amir
Amir

Reputation: 2011

I think you might be looking for the endswith operator.

Try using [x for x in smalllist if x.endswith("PRO7")]

Upvotes: 3

Related Questions