繁体   English   中英

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

[英]Check for elements in one list from another list

下面的代码尝试扫描mag的所有元素以查找note的所有元素。 如果可以在mag中找到note的所有UNIQUE元素,则应打印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 =“否,无法在mag中找到所有n个元素” ..但事实并非如此,因为在list(mag)和list(两者中,元素“ two”的频率均为2注意)

我要实现的目标:我想比较note中的每个唯一元素是否都可以在mag中找到。 例如,如果mag = [“ a”,“ b”,“ c”,“ d”]和note = [“ b”,“ a”,“ c”] ..,它将返回TRUE。 但如果mag = [“ a”,“ b”,“ c”,“ d”]且note = [“ b”,“ a”,“ a”“ c”],则返回false,因为“ a”出现两次在笔记中,但一次

检查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-验证一个列表是否为另一个列表的子集

使用Counter来计数每个单词中每个单词出现的次数,然后我相信您的检查归结为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM