如何从嵌套列表中删除小于给定长度的条目

How to remove entries from a nested list that are shorter than a given length

我有一个包含多个子列表的嵌套列表,如下所示:

l = [
    ...
    ['22.06.2009', 'https://hoew.de/ha/xx']
    ...
    ]

但也有一些条目,例如:

U= [
    ...
   ['22.06.2009', '/']
   ['22.06.2009', 'hiw']
   ...
   ]

现在我想删除在 [1] 索引处的条目太短(少于 5 个字符)的子列表。

我该怎么做?

您可以执行以下列表理解:

>>> l = [
    ['22.06.2009', 'https://hoew.de/ha/xx'],
    ['22.06.2009', '/'],
    ['22.06.2009', 'hiw']
    ]

>>> [x for x in l if len(x[1]) >= 5]
[['22.06.2009', 'https://hoew.de/ha/xx']]

可以通过矩阵做一个列表推导,我们可以称之为unfiltered_matrix,一个candidate只有他的第二个元素的长度大于5才可以考虑,结果会成为 filtered_matrix.

filtered_matrix = [candidate for candidate in unfiltered_matrix if len(candidate[1] >= 5)]