[英]Python - Check if element is in 1 or more nested lists and return whole list if TRUE
在此先感謝您的幫助。
我有一個嵌套列表/列表列表,只有當列表包含特定元素時,我才需要將每個列表返回到屏幕。
榜單特點:
index 0 = fruit name, index 1 = amount, index 2 = colour
。lists = [banana, 10, yellow], [apple, 12, red], [pear, 60, green], [mango, 5, yellow]
我嘗試過條件 for 循環和為每個變體創建一個新列表的想法,但這似乎是一個難以管理的解決方案。
誰能幫忙?
搜索 1:如果 'banana' 在一個或多個嵌套列表中 然后打印每個嵌套列表
預期 output:[香蕉,10,黃色]
搜索 2:如果 'yellow' 在一個或多個嵌套列表中 然后打印每個嵌套列表
預期 output:[香蕉,10,黃色] [芒果,5,黃色]
這是一個粗略的方法:
lists = [
["banana", 10, "yellow"],
["apple", 12, "red"],
["pear", 60, "green"],
["mango", 5, "yellow"],
]
keyword = 'banana'
for lst in lists:
if keyword in lst:
print(lst)
keyword = 'yellow'
for lst in lists:
if keyword in lst:
print(lst)
理想情況下,您會將搜索提取到接受列表和關鍵字的 function:
def get_sublists_containing_keyword(lists, keyword):
sublists = []
for lst in lists:
if keyword in lst:
sublists.append(lst)
return sublists
lists = [
["banana", 10, "yellow"],
["apple", 12, "red"],
["pear", 60, "green"],
["mango", 5, "yellow"],
]
banana_lists = get_sublists_containing_keyword(lists, 'banana')
yellow_lists = get_sublists_containing_keyword(lists, 'yellow')
for banana_list in banana_lists:
print(banana_list)
for yellow_list in yellow_lists:
print(yellow_list)
)你可以使用str. join( )
) inside a f-string
to remove the single quote characters around the string elements when you print: str. join( )
inside a f-string
以在打印時刪除字符串元素周圍的單引號字符:
def print_lists_that_contain_search_term(lists: list[list[str | int]],
search_term: str) -> None:
print(f'{search_term = }')
print(' '.join(f'[{", ".join(map(str, lst))}]' for lst in lists if search_term in lst))
def main() -> None:
lists = [['banana', 10, 'yellow'], ['apple', 12, 'red'], ['pear', 60, 'green'], ['mango', 5, 'yellow']]
print_lists_that_contain_search_term(lists, 'banana')
print_lists_that_contain_search_term(lists, 'yellow')
if __name__ == '__main__':
main()
Output:
search_term = 'banana'
[banana, 10, yellow]
search_term = 'yellow'
[banana, 10, yellow] [mango, 5, yellow]
這是一個單一的班輪解決方案。
def search(lists, item):
return list(filter(None, map(lambda x: x if item in x else [], lists)))
現在可以撥打function查詢。
In [12]: lists
Out[12]:
[['banana', 10, 'yellow'],
['apple', 12, 'red'],
['pear', 60, 'green'],
['mango', 5, 'yellow']]
In [13]: search(lists, 'banana')
Out[13]: [['banana', 10, 'yellow']]
In [14]: search(lists, 'yellow')
Out[14]: [['banana', 10, 'yellow'], ['mango', 5, 'yellow']]
在這里,我使用了 lambda 表達式並檢查待搜索項是否在列表中,然后返回該列表,否則返回一個空列表。 並通過過濾器 Function 刪除了所有空列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.