如果嵌套列表在索引处包含数字,则删除嵌套列表

Remove nested list if nested list contains a number at an index

如果嵌套列表在特定索引处包含特定数字,我想删除该数字嵌套列表。

列表示例:

permutations_list = [[9, 7, 14, 4, 2, 10], [9, 7, 2, 10, 14, 4], [9, 7, 2, 10, 4, 14], [9, 7, 2, 14, 10, 4], [9, 7, 2, 14, 4, 10], [9, 7, 2, 4, 10, 14], [9, 7, 2, 4, 14, 10], [9, 7, 4, 10, 14, 2], [9, 7, 4, 10, 2, 14], [9, 7, 4, 14, 10, 2], [9, 7, 4, 14, 2, 10], [9, 7, 4, 2, 10, 14], [9, 7, 4, 2, 14, 10]]

我想检查每个嵌套列表是否在索引 4 处包含数字 14。如果出现这种情况,请删除任何符合这些规范的嵌套列表,从而生成以下列表:

permutations_list = [[9, 7, 14, 4, 2, 10], [9, 7, 2, 10, 4, 14], [9, 7, 2, 14, 10, 4], [9, 7, 2, 14, 4, 10], [9, 7, 2, 4, 10, 14], [9, 7, 4, 10, 2, 14], [9, 7, 4, 14, 10, 2], [9, 7, 4, 14, 2, 10], [9, 7, 4, 2, 10, 14]]

这是我尝试过的:

for i in permutations_list:
    for c in i:
        if c =='10' and c[4]:
            permutations_list.remove(i)

这一切的结果是:

TypeError: 'int' object is not subscriptable

使用列表理解

例如:

permutations_list = [[9, 7, 14, 4, 2, 10], [9, 7, 2, 10, 14, 4], [9, 7, 2, 10, 4, 14], [9, 7, 2, 14, 10, 4], [9, 7, 2, 14, 4, 10], [9, 7, 2, 4, 10, 14], [9, 7, 2, 4, 14, 10], [9, 7, 4, 10, 14, 2], [9, 7, 4, 10, 2, 14], [9, 7, 4, 14, 10, 2], [9, 7, 4, 14, 2, 10], [9, 7, 4, 2, 10, 14], [9, 7, 4, 2, 14, 10]]
permutations_list = [i for i in permutations_list if not i[4] == 14]
print(permutations_list)

或使用filter

permutations_list = list(filter(lambda x: x[4] != 14, permutations_list))

输出:

[[9, 7, 14, 4, 2, 10],
 [9, 7, 2, 10, 4, 14],
 [9, 7, 2, 14, 10, 4],
 [9, 7, 2, 14, 4, 10],
 [9, 7, 2, 4, 10, 14],
 [9, 7, 4, 10, 2, 14],
 [9, 7, 4, 14, 10, 2],
 [9, 7, 4, 14, 2, 10],
 [9, 7, 4, 2, 10, 14]]

你可以只遍历主列表一次,并检查此列表中索引 4 处的元素是否为 14。如果是 14,则将其删除,如果不是,则什么都不做。就像我在下面做的那样

for i in permutations_list :
   if i[4] == 14 :
      permutations_list.remove(i)