簡體   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