Python - 檢查一個列表是否包含在另一個列表中
給定兩個不同的 python 列表,我們需要確定第一個列表是否是第二個列表的一部分。
使用 map 和 join
我們可以首先應用 map 函式以獲取列表元素,然後應用 join 函式建立以逗號分隔的值的列表。接下來,我們使用 in 運算子以確定第一個列表是否是第二個列表的一部分。
示例
listA = ['x', 'y', 't'] listB = ['t', 'z','a','x', 'y', 't'] print("Given listA elemnts: ") print(', '.join(map(str, listA))) print("Given listB elemnts:") print(', '.join(map(str, listB))) res = ', '.join(map(str, listA)) in ', '.join(map(str, listB)) if res: print("List A is part of list B") else: print("List A is not a part of list B")
輸出
執行上述程式碼後,會得到以下結果 -
Given listA elemnts: x, y, t Given listB elemnts: t, z, a, x, y, t List A is part of list B
使用 range 和 len
我們可以設計一個 for 迴圈來檢查表單的一個列表中的元素是否存在於另一個列表中,方法是使用 range 函式和 len 函式。
示例
listA = ['x', 'y', 't'] listB = ['t', 'z','a','x', 'y', 't'] print("Given listA elemnts: \n",listA) print("Given listB elemnts:\n",listB) n = len(listA) res = any(listA == listB[i:i + n] for i in range(len(listB) - n + 1)) if res: print("List A is part of list B") else: print("List A is not a part of list B")
輸出
執行上述程式碼後,會得到以下結果 -
Given listA elemnts: ['x', 'y', 't'] Given listB elemnts: ['t', 'z', 'a', 'x', 'y', 't'] List A is part of list B
廣告