繁体   English   中英

如何通过嵌套列表中第一个元素的值提取子列表

[英]How to extract a sublist by the value of the first element from a nested list

我想根据每个列表中的第一个元素从嵌套列表中提取一个子列表。 我有以下嵌套列表:

input = [
    ['nom', 'N', 'eye'],
    ['acc', 'E', 'computer'],
    ['dat', 'C', 'screen']
    ]

我想要一个 function 在输入子列表'nom'的第一个元素时返回['nom', 'N', 'eye'] ,例如:

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  

我应该如何使用 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']

假设参数在输入的第一个索引中,那么代码是:

output = []
def extract_sublist(keyword: str):
    for li in input_list:
        if keyword == li[0]:
            output.append(li[0:])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM