Vit*_*ira 12 python python-3.x
我一开始就知道这是一个非常普遍的问题,但我还没有找到一个具体的问题。(如果您愿意,请告诉我。)而我发现的所有方式都不适合我。我需要检查列表1中的所有元素是否在列表2中以相同的数量出现。
例如:
#If list1 = [2,2,2,6]
# and list2 =[2,6,2,5,2,4]
#then all list1 are in list2.
#If list2 = [2,6] then all list1 are not in list2.
Run Code Online (Sandbox Code Playgroud)
我正在尝试这种方式:
list1 = [6,2]
import itertools
for i in itertools.product((2,4,5,1), repeat=3) :
asd = i[0] + i[1]
asd2= i[1] + i[2]
list2 = [asd, asd2]
if all(elem in list2 for elem in list1):
print (i,list2)
Run Code Online (Sandbox Code Playgroud)
当list1中的元素不重复时,它可以工作,例如[1,2]。但是当它们重复时,所有重复的元素仅被计为1:[2,2,2],其蜜蜂被理解为[2]。还是我想。
gil*_*lch 17
使用collections.Counter
要转换为dict_items
的(值,数量)对视图设置。然后,您可以使用常规设置操作。
from collections import Counter
def a_all_in_b(a, b):
"""True only if all elements of `a` are in `b` in the *same quantity* (in any order)."""
return Counter(a).items() <= Counter(b).items()
Run Code Online (Sandbox Code Playgroud)
请注意,Counter
它仅适用于可散列的元素,因为它是的子类dict
。