Home > Blockchain >  How to get list which contains certain element from lists of lists
How to get list which contains certain element from lists of lists

Time:09-17

Is there a more efficient way to to return a list that contains 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']

This is what I've tried:

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

This returns the list where the element is but I would like to know if there is a more efficient way.

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:

I think this would work!

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

Let me know if that helped!

CodePudding user response:

A different approach is to use a lambda function combined with a list comprehension:

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

f = lambda x: [subl for subl in lists if x in subl]

f('A')  # [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['A', 'C']]
  • While in the case no letter can appear in multiple lists:
lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]

f = lambda x: [subl for subl in lists if x in subl][0]
    
f('A')  # ['A', 'B', 'D', 'E', 'F', 'G', 'H']
f('C')  # ['C']
  • Related