Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

python - check if a list subset of another list (values can be repetative)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...