共計(jì) 507 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
可以使用嵌套列表的循環(huán)和條件語句來查找元素。以下是一個(gè)使用 Python 的嵌套列表查找元素的示例代碼:
def find_element(nested_list, target):
for sublist in nested_list:
for element in sublist:
if element == target:
return True
return False
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
if find_element(nested_list, target):
print(f" 元素 {target} 存在于嵌套列表中 ")
else:
print(f" 元素 {target} 不存在于嵌套列表中 ")
輸出結(jié)果為:
元素 5 存在于嵌套列表中
該示例代碼中的 find_element
函數(shù)接受一個(gè)嵌套列表和目標(biāo)元素作為參數(shù)。函數(shù)使用兩層循環(huán)遍歷嵌套列表,并使用條件語句判斷每個(gè)元素是否等于目標(biāo)元素。如果找到目標(biāo)元素,函數(shù)返回 True
,否則返回False
。在示例代碼的末尾,我們調(diào)用find_element
函數(shù)來檢查目標(biāo)元素是否存在于嵌套列表中,并根據(jù)結(jié)果輸出相應(yīng)的信息。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完