如果嵌套的数字列表在特定索引处包含特定数字,我想删除该列表。
列表示例列表:
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)