Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to check if the list List2 is a subset of List1 in python 3.8

I tried all() and issubset() functions and they all fail to filter it as I wanted - they give True, unfortunately - elements of two actually not all in one, are they?

List1 = [1,  4, 1, 3, 5]
 
List2 = [1 , 1, 1]

What I tried:

check =  all(item in List1 for item in List2)

failed, returns True.

flag = 0
if(set(List2).issubset(set(List1))): 
    flag = 1
print(flag)

failed, returns True.

Also using intersection() gives True (actually I don't want intersection).

What is the solution for this? Have not checked Numpy yet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

Using Counter

from collections import Counter 
  
def is_second_list_in_first(first_list, second_list): 
    ' checks if 2nd list of elements is in first list of elemetns with sufficient counts  '
     # get counts of two lists
    count_first = Counter(first_list) 
    count_second = Counter(second_list) 
  
    # check if count of elements exists in first list
    return all(count_second[key] <= count_first[key] for key in count_second)
    
# Tests
print(is_second_list_in_first([1,  4, 1, 3, 5], [1]))        # True
print(is_second_list_in_first([1,  4, 1, 3, 5], [1, 1]))     # True
print(is_second_list_in_first([1,  4, 1, 3, 5], [1, 1, 1]))  # False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...