[英]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)
您可能需要兩個不同的函數,一個返回包含搜索元素的所有子列表,一個只返回包含搜索元素的第一個子列表(如果存在):
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.