Python – Selecting elements of list b containing elements of list a
Question:
There is a_list and b_list. We are in the process of sorting out only the b_list elements that contain elements of a_list.
a = ["Banana", "Orange", "Almond", "Kiwi", "Cabbage"]
b = [["Banana", "Pencil", "Water Bucket"], ["Orange", "Computer", "Printer"], ["Snail", "Cotton Swab", "Sweet Potato"]]
c = []
If the first element of list in b_list matches an element of list a_, this list element is put into c_list.So the desired result is
c = [["Banana", "Pencil", "Water Bucket"], ["Orange", "Computer", "Printer"]]
I’ve searched several posts, but couldn’t find an exact match, so I’m leaving a question. help
Answers:
Here’s your answer
for i in b:
if i[0] in a:
c.append(i)
a = [i for i in range(1, 10)]
b = [[1, 10, 100], [2, 20, 200], [10, 100, 1000]]
c = []
for sublist in b:
if sublist[0] in a:
c.append(sublist)
>>> c
[[1, 10, 100], [2, 20, 200]]
c =[i for i in b if i[0] in a]
There is a_list and b_list. We are in the process of sorting out only the b_list elements that contain elements of a_list.
a = ["Banana", "Orange", "Almond", "Kiwi", "Cabbage"]
b = [["Banana", "Pencil", "Water Bucket"], ["Orange", "Computer", "Printer"], ["Snail", "Cotton Swab", "Sweet Potato"]]
c = []
If the first element of list in b_list matches an element of list a_, this list element is put into c_list.So the desired result is
c = [["Banana", "Pencil", "Water Bucket"], ["Orange", "Computer", "Printer"]]
I’ve searched several posts, but couldn’t find an exact match, so I’m leaving a question. help
Here’s your answer
for i in b:
if i[0] in a:
c.append(i)
a = [i for i in range(1, 10)]
b = [[1, 10, 100], [2, 20, 200], [10, 100, 1000]]
c = []
for sublist in b:
if sublist[0] in a:
c.append(sublist)
>>> c
[[1, 10, 100], [2, 20, 200]]
c =[i for i in b if i[0] in a]