Home > Back-end >  How to return a list which contains certain element from lists of lists
How to return a list which contains certain element from lists of lists

Time:09-20

Is there a more efficient way to return a list that contains a certain element from a list of lists?

For example:

lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]

If my input is C return the list ['C'] or if my input is D return the list = ['A', 'B', 'D', 'E', 'F', 'G', 'H']

What I've tried:

for lst in lists: 
    for n in range(len(lst)):
        if element == lst[n]:
            print(lst)

This is inefficient and I would like to know how to make it more efficient.

CodePudding user response:

It might help you:

lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]
for lst in lists:
    if element in lst:
        print(lst)

CodePudding user response:

You can try this:

for lst in lists:
    if element in lst:
        print(lst)

CodePudding user response:

You can try this.

lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]

user_input = input("Please enter your input: ")

for item in lists:
    if user_input in item:
        print(item)
        break

CodePudding user response:

You should use the in operator:

def foo(lists, element):
    for l in lists:
        if element in l:
            return l
print(foo([['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']], 'C')) #prints ['C']
print(foo([['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']], 'D')) #prints ['A', 'B', 'D', 'E', 'F', 'G', 'H']

Let me know if that helped!

Summary of answer: I used a function with parameters as the list, and the element. Basically I looped through each list in the list of lists, and checked if the element is in each list. If so, I return that list.

CodePudding user response:

A different approach: a lambda function combined with a list comprehension:

  • in the case where a letter can appear in multiple lists:
lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['A', 'C']]

find_lists = lambda x, input_list: [sublist for sublist in input_list if x in sublist]

find_lists('A', lists)  # [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['A', 'C']]
  • in the case where no letter can appear in multiple lists, the looping can return at the first finding:
lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]

def find_list(x, input_list) -> list:
    for sublist in input_list:
        if x in sublist:
            return sublist
    
find_list('A', lists)  # ['A', 'B', 'D', 'E', 'F', 'G', 'H']
find_list('C', lists)  # ['C']

  • Related