繁体   English   中英

搜索元素并返回列表列表中的列表

[英]search an element and return the list within list of lists

我有以下清单

list_of_lists= [
    ['ID', 'Last', 'First', 'GradYear', 'GradTerm', 'DegreeProgram'],
    ['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA']
]

现在,当我输入例如101010 ,我想检索['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA'] - 我该怎么做?

您将需要搜索内部列表而不是整个列表。

input = '101010'

for lst in list_of_lists:
    if input in lst:
        # Do what you want with the list containing the input

您可以简单地使用in

list_of_lists= [
    ['ID', 'Last', 'First', 'GradYear', 'GradTerm', 'DegreeProgram'],
    ['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA']
]

needle = '101010'
result = [lst for lst in list_of_lists if needle in lst]
print(result)

在 ideone.com 上查看演示

您可能需要两个不同的函数,一个返回包含搜索元素的所有子列表,一个只返回包含搜索元素的第一个子列表(如果存在):

def get_all_lists_with_element(list_of_lists: list[list[str]],
                               element: str) -> list[list[str]]:
    """Returns all sub-lists that contain element"""
    return [xs for xs in list_of_lists if element in xs]


def get_first_list_with_element(list_of_lists: list[list[str]],
                                element: str) -> list[str]:
    """Returns first sub-list that contains element"""
    return next((xs for xs in list_of_lists if element in xs), None)


list_of_lists = [
    ['ID', 'Last', 'First', 'GradYear', 'GradTerm', 'DegreeProgram'],
    ['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA'],
    ['101010'],
]

input_str = input('Enter string to search for in list of lists: ')
all_lists_with_input = get_all_lists_with_element(list_of_lists, input_str)
print(f'all_lists_with_input={all_lists_with_input}')
first_list_with_input = get_first_list_with_element(list_of_lists, input_str)
print(f'first_list_with_input={first_list_with_input}')

输入存在的示例用法:

Enter string to search for in list of lists: 101010
all_lists_with_input=[['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA'], ['101010']]
first_list_with_input=['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA']

输入不存在的示例用法:

Enter string to search for in list of lists: abc
all_lists_with_input=[]
first_list_with_input=None

这可能会帮助你

def complete_list(input, list_of_lists):
    for i in list_of_lists:
        if input in i:
            return i
    return None

如果您有任何问题,请随时提问

ll = [
    ['ID', 'Last', 'First', 'GradYear', 'GradTerm', 'DegreeProgram'],
    ['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA']
]

y = next((x for x in ll if '101010' in x), [])

['101010'、'李'、'Shane'、'2019'、'春天'、'MSA']

filter也有效,特别是如果您想查找所有匹配项:

list_of_lists= [
    ['ID', 'Last', 'First', 'GradYear', 'GradTerm', 'DegreeProgram'],
    ['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA']
]
find = '101010'
res = list(filter(lambda x: find in x, list_of_lists))
print(res)

暂无
暂无

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

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