[英]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.