从另一个列表中检查一个列表中的元素

Check for elements in one list from another list

以下代码尝试扫描 mag 的所有元素以查找所有 note 元素。如果 note 的所有 UNIQUE 元素都可以在 mag 中找到,那么它应该打印 YES ..否则它应该打印 NO。 元素检查应该区分大小写。

mag =['two', 'times', 'three', 'is', 'not', 'four', 'two']
note =['two', 'times', 'two', 'is', 'four']
r = ""
x=[]
for i in mag:
    for j in note:
        if j in i and j not in x:
            x.append(j)
    if len(x)==len(note):
        r = "YES, all note elements can be found in mag"
    else:
        r = "NO, all note elements cannot be found in mag"
print(r)
print (" ".join(map(str, x)))

当我 运行 代码时,我得到 r = "NO, all n elements cannot be found in mag" .. 但事实并非如此,因为元素 "two" 的频率在两个列表中都是 2(mag ) 和列表(注)

我想达到的效果: 我想比较note中的每一个独特的元素是否都可以在mag中找到。例如如果 mag=["a"、"b"、"c"、"d"] 并且注释 = ["b"、"a"、"c"] .. 它将 return 正确。但是如果 mag=["a", "b", "c", "d"] 并且 note = ["b", "a", "a" "c"] 那么它 return false 因为 "a" 在 note 中出现两次,而在 mag

中出现一次

检查 list1 的所有元素是否都在 list2 中的一种简单的临时方法是使用

def check_subset(list1, list2):
    for item in list1:
        if item not in list2:
            return False
    return True

或者作为使用列表理解的单行者:

all([item in list2 for item in list1])

更好的方法是使用集合,例如看这里: Python - verifying if one list is a subset of the other

用一个Counter来统计每个单词出现了多少次,然后我相信你的检查归结为note的计数器是否小于note的计数器的问题mag,但不幸的是,计数器并没有像我想的那样实现 <=。您必须手动比较它们:

from collections import Counter

counter_note = Counter(note)
counter_mag = Counter(mag)

if all(counter_mag.get(word, 0) >= count for word, count in counter_note.items()):
    r = "YES, all note elements can be found in mag"
else:
    r = "NO, all note elements cannot be found in mag"

不是单行,因为您必须首先确定较短的列表。如果你总是知道 note 的元素少于 mag,那么你可以跳过这个测试。

a = [note, mag][len(mag) > len(note)]         #more list elements
b = [note, mag][mag != a]                     #less list elements

print(all([a.count(item) >= b.count(item) for item in set(b)]))

输出

mag =['two', 'times', 'three', 'is', 'not', 'four', 'two']
note =['two', 'times', 'two', 'is', 'four']
>>>True

mag =['two', 'times', 'three', 'is', 'not', 'five']
note =['two', 'times', 'two', 'is', 'four']
>>>False