简体   繁体   English

Python - 选择列表 b 中包含列表 a 元素的元素

[英]Python - Selecting elements of list b containing elements of list a

There is a_list and b_list.有a_list 和b_list。 We are in the process of sorting out only the b_list elements that contain elements of a_list.我们正在仅对包含 a_list 元素的 b_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如果 b_list 中列表的第一个元素与列表 a_ 的元素匹配,则将该列表元素放入 c_list 中。所以想要的结果是

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帮助

c =[i for i in b if i[0] in a]

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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM