I want to extract a sublist from a nested list based on the first element in each list. I have the following nested list:
input = [
['nom', 'N', 'eye'],
['acc', 'E', 'computer'],
['dat', 'C', 'screen']
]
I want to have a function which returns ['nom', 'N', 'eye']
when the first element of the sublist 'nom'
is inputted, for instance:
output = ['nom', 'N', 'eye'] # When the function takes 'nom' as its argument
output = ['acc', 'E', 'computer'] # When the function takes 'acc' as its argument
output = ['dat', 'C', 'screen'] # When the function takes 'dat' as its argument
How should I achieve this with python3.6+?
my_list = [
['nom', 'N', 'eye'],
['acc', 'E', 'computer'],
['dat', 'C', 'screen']
]
my_input = input("Enter first string to find: ")
for lis in my_list:
if lis[0] == my_input:
print(lis)
break
Output:
Enter variable name: nom
['nom', 'N', 'eye']
Assuming that the argument is in the first index of input then the code is:
output = []
def extract_sublist(keyword: str):
for li in input_list:
if keyword == li[0]:
output.append(li[0:])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.