I want to extract a sublist from a nested list based on the first element in each list. I have the following nested list:
JavaScript
x
6
1
input = [
2
['nom', 'N', 'eye'],
3
['acc', 'E', 'computer'],
4
['dat', 'C', 'screen']
5
]
6
I want to have a function which returns ['nom', 'N', 'eye']
when the first element of the sublist 'nom'
is inputted, for instance:
JavaScript
1
4
1
output = ['nom', 'N', 'eye'] # When the function takes 'nom' as its argument
2
output = ['acc', 'E', 'computer'] # When the function takes 'acc' as its argument
3
output = ['dat', 'C', 'screen'] # When the function takes 'dat' as its argument
4
How should I achieve this with python3.6+?
Advertisement
Answer
JavaScript
1
12
12
1
my_list = [
2
['nom', 'N', 'eye'],
3
['acc', 'E', 'computer'],
4
['dat', 'C', 'screen']
5
]
6
my_input = input("Enter first string to find: ")
7
8
for lis in my_list:
9
if lis[0] == my_input:
10
print(lis)
11
break
12
Output:
JavaScript
1
3
1
Enter variable name: nom
2
['nom', 'N', 'eye']
3