我想創建一個函式來確定給定數字是否在數字串列中。如何修復以下代碼以使其適用于由串列組成的串列?
lst = [[1, 2], [3, 4],[5, 6, 7]]
num = 9
def in_list_of_list(lst: list) -> bool:
i = 0
while i < len(lst) and lst[i] != num:
i = i 1
return i < len(lst)
print(in_list_of_list(lst))
uj5u.com熱心網友回復:
您可以先展平串列,然后在展平的串列中輕松檢查:
lst = [[1, 2], [3, 4], [5, 6, 7]]
num = 9
def in_list_of_list(lst: list) -> bool:
flat_list = [item for sublist in lst for item in sublist]
return num in flat_list
print(in_list_of_list(lst))
uj5u.com熱心網友回復:
您詢問該專案是否在串列的任何元素內
def in_list_of_list(lst: list, item:object) -> bool:
for sublist in lst:
if item in sublist:
return True
return False
和快速測驗
>>> lst = [[1, 2], [3, 4],[5, 6, 7]]
>>> in_list_of_list(lst, 9)
False
>>> in_list_of_list(lst, 7)
True
>>>
uj5u.com熱心網友回復:
lst = [[1, 2], [3, 4],[5, 6, 7]]
num = 9
def in_list_of_list(lst: list) -> bool:
new_lst = []
for a in lst:
new_lst.extend(a) # add element from the inner list to new_list.
return num in new_lst # return True if the num inside the list else False.
print(in_list_of_list(lst))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/468585.html
上一篇:如何根據其平均值轉換/轉換列并將其反映在R中的圖表上?
下一篇:回圈查詢直到找到結果
