簡體   English   中英

如何在 Python 中輕松檢查一個列表中的所有項目都包含在另一個列表中?

[英]How can I easily check in Python that all items in one list are included in the other list?

我找到了一些解決方案,但沒有一個是我需要的。

例如:

list1 = ['a', 'b', 'c']
list2 = ['a', 'a', 'b', 'c']

Counter(list1) == Counter(list2) -> True ,但我需要False因為雙 'a' //// set(list1) == set(list2) -> True ,但我也需要False

我想編寫一個小代碼來從列表中搜索可能的單詞。

例子:

wordCollection = ["dog", "go", "home", "long"] //// 輸入字符:"NLGUCOBAD"

結果:狗,go,長

您可以將all與一個簡單的表達式結合使用:

result = all((list1.count(x) == list2.count(x)) for x in list1)

如果集合中的每個項目都是True ,則all返回True 當不是每個項目都為True時,它也將返回False

例如:

all([True, True, True, True, True])
>>> True

all([True, False, True, True, True])
>>> False

考慮到這一點,您可以檢查list1中每個元素的計數是否與list2中的相同。 這就是list1.count(x) == list2.count(x)的來源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM