Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I return a list from a list of lists when searching a string and also force the comparison to lowercase?

I have a list of lists as such:

allTeams = [ [57, 'Arsenal FC', 'Arsenal', 'ARS'], [58, 'Aston Villa FC', 'Aston Villa', 'AVL'], [61, 'Chelsea FC', 'Chelsea', 'CHE'], ...]

userIsLookingFor = "chelsea"
    
for team in allTeams:
    if userIsLookingFor.lower() in any_element_of_team.lower():
        print(team)
  

> [61, 'Chelsea FC', 'Chelsea', 'CHE']

I would basically look for the user’s requested word in a list of lists, and if there’s a match, I print that list. In the case above, the user searches for "chelsea" and in one of the lists, there’s a match for "chelsea" (either Chelsea FC or Chelsea, doesn’t matter). So I would return that specific list.

I tried using "any" but it seems to only return a boolean and I can’t actually print any list from it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a list comprehension:

userIsLookingFor = "chelsea"

# option 1, exact match item 2
[l for l in allTeams if l[2].lower() == userIsLookingFor]


# option 2, match on any word
[l for l in allTeams
 if any(x.lower() == userIsLookingFor
        for s in l if isinstance(s, str)
        for x in s.split())
]

output:

[[61, 'Chelsea FC', 'Chelsea', 'CHE']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading