I would like to see if all items from one list of list (List A) that appears from another list of list (List B - a full list), then save the return true or false to a list.
For example, here are two lists (list of list) below
List A : [ [1,2],[3,4],[8,9] ]
List B : [ [1,2,3,4], [5,6,7],[8,10] ]
Expected Result
Result List : [[True,False,False]
You can use the following code:
A = [ [1,2],[3,4],[8,9] ]
B = [ [1,2,3,4], [5,6,7],[8,10] ]
result = []
for x,y in zip(A, B):
if all(e in y for e in x):
result.append(True)
else:
result.append(False)
which produces a list as the following:
[True, False, False]
The code uses zip()
function which pairs corresponding items from the two lists together.
Also, the line all(e in y for e in x)
is the essential part of the code. It checks if all elements in the first sub-list of A are in the first sub-list B, and so on.
You can use zip()
along with issubset()
method on set
as follows:
[True if set(x).issubset(set(y)) else False for x,y in zip(a,b)]
Performance wise I don't think this is better that ammar's answer. But this is a one liner ;-)
Using issubset()
A = [[1,2],[3,4],[8,9]]
B = [[1,2,3,4], [5,6,7],[8,10]]
result = [True if set(i[0]).issubset(i[1]) else False for i in list(zip(A,B))]
print(result)
# 158 µs ± 14.7 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Output:
[True, False, False]
Try list-comprehension
and zip
:
a = [ [1,2],[3,4],[8,9] ]
b = [ [1,2,3,4], [5,6,7],[8,10] ]
result = [True if set(i[0]).issubset(set(i[1])) else False for i in zip(a,b) ]
print(result)
Output :
C:\Users\Desktop>py x.py
[True, False, False]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.