[英]Remove a list in a list of lists based on condition
I have the following list of lists:我有以下列表列表:
lst = [['a',102, True],['b',None, False], ['c',100, False]]
I'd like to remove any lists where the value in the second position is None.我想删除第二个位置的值为 None 的所有列表。 How can I do this (in a list comprehension)
我该怎么做(在列表理解中)
I've tried a few different list comprehension but can't seem to figure it out.我尝试了几种不同的列表理解,但似乎无法弄清楚。 Thanks!
谢谢!
Try this:试试这个:
lst = [item for item in lst if item[1] is not None]
Use this:用这个:
lst = (('a',102, True),('b',None, False), ('c',100, False))
lst = tuple([el for el in lst if el[1] is not None])
print(lst) # => (('a', 102, True), ('c', 100, False))
Your data is a tuple of tuples, not a list of lists, so you need to convert it to a tuple at the end.您的数据是元组的元组,而不是列表的列表,因此您需要在最后将其转换为元组。
Use filter
and lambda
to generate new tuple if lement in index 1 (second position) of inner tuple not equals None
:如果内部元组的索引 1(第二个位置)中的元素不等于
None
,则使用filter
和lambda
生成新元组:
lst = tuple(filter(lambda i: i[1] != None, lst))
# (('a', 102, True), ('c', 100, False))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.