首页 > 解决方案 > 如何摆脱此列表中的子元组?

问题描述

list_of_tuple = [(0,2), (0,6), (4,6), (6,7), (8,9)]

由于(0,2)&(4,6)都在 的索引内(0,6),所以我想删除它们。结果列表将是:

list_of_tuple = [(0,6), (6,7), (8,9)]

看来我需要以某种方式对这个列表元组进行排序以使其更容易删除。但是如何对元组列表进行排序?

给定两个数组索引元组[m,n][a,b],如果:

m >=a & n<=b

然后[m,n]包含在 中[a,b],然后[m,n]从列表中删除。

标签: pythonlist

解决方案


要从list_of_tuples指定元组之外的范围内删除所有元组:

list_of_tuple = [(0,2), (0,6), (4,6), (6,7), (8,9)]

def rm(lst,tup):
    return [tup]+[t for t in lst if t[0] < tup[0] or t[1] > tup[1]]

print(rm(list_of_tuple,(0,6)))

输出:

[(0, 6), (6, 7), (8, 9)]

推荐阅读