Home > Enterprise >  How can I return a list from a list of lists when searching a string and also force the comparison t
How can I return a list from a list of lists when searching a string and also force the comparison t

Time:05-18

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.

CodePudding user response:

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']]
  • Related