Reputation: 65
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.
Upvotes: 0
Views: 1328
Reputation: 151
Your welcome:
lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]
element ='D'
lst = [lst for lst in lists if element in lst]
print(lst)
Upvotes: 0
Reputation: 384
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.
Upvotes: 0
Reputation: 61
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
Upvotes: 0
Reputation: 41
You can try this:
for lst in lists:
if element in lst:
print(lst)
Upvotes: 1
Reputation: 352
It might help you:
lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]
for lst in lists:
if element in lst:
print(lst)
Upvotes: 3