[英]How to extract a sublist from a list where the last character of the previous element is the same as the first character of the last element? - python
[英]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.