简体   繁体   English

找到列表中的变量时,Python 从列表中返回列表

[英]Python return list out of list of lists when variable in list is found

I'm a Python beginner.我是 Python 初学者。 I'm trying to return a list from a list of lists into a new list of lists.我正在尝试将列表列表中的列表返回到新的列表列表中。 I've looked extensively at similar questions, but cannot find the answer.我已经广泛地查看了类似的问题,但找不到答案。

l1 = [['a','b','c','d'],['b','c','d','f'],['b','c','a','f']]

I would like to loop over l1 to check if 'a' is in a list, and when true then add that list to a new list of lists l2.我想遍历 l1 以检查“a”是否在列表中,如果为真,则将该列表添加到列表 l2 的新列表中。 I got this far (not very far):我走了这么远(不是很远):

l2 = []
for selector in l1:
    if 'a' in selector:
        l2.append(*#I don't know this part*)

What i would like is this result:我想要的是这个结果:

l2 = [['a','b','c','d'],['b','c','a','f']]

Any help would be much appreciated.任何帮助将非常感激。

You can use a list comprehension to iterate over the inner lists您可以使用列表理解来迭代内部列表

>>> [sub for sub in l1 if 'a' in sub]
[['a', 'b', 'c', 'd'], ['b', 'c', 'a', 'f']]

To complete the snippet of code you showed above, the way you'd use a for loop is要完成上面显示的代码片段,您使用for循环的方式是

l2 = []
for selector in l1:
    if 'a' in selector:
        l2.append(selector)

>>> l2
[['a', 'b', 'c', 'd'], ['b', 'c', 'a', 'f']]

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

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