【问题标题】:Python return list out of list of lists when variable in list is found找到列表中的变量时,Python从列表列表中返回列表
【发布时间】:2017-10-16 11:04:13
【问题描述】:

我是 Python 初学者。我正在尝试将列表中的列表返回到新的列表列表中。我已经广泛研究了类似的问题,但找不到答案。

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

我想遍历 l1 以检查“a”是否在列表中,如果为真,则将该列表添加到列表 l2 的新列表中。我走了这么远(不是很远):

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

我想要的是这样的结果:

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

任何帮助将不胜感激。

【问题讨论】:

  • result.append(selector)?

标签: python python-3.x list for-loop


【解决方案1】:

您可以使用列表推导来迭代内部列表

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

要完成上面显示的代码的 sn-p,使用 for 循环的方式是

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

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

【讨论】:

  • 哇,谢谢,解决了!我看到我自己到那里只有一个字。有点尴尬
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
相关资源
最近更新 更多