gpt4 book ai didi

python - 从列表中删除一个子列表,其中数字已经存在于另一个子列表中

转载 作者:行者123 更新时间:2023-11-28 22:46:08 25 4
gpt4 key购买 nike

给定一个列表t:

[[0, 4], [0, 4, 5, 7], [1, 2, 3, 6], [1, 3], [2, 6], [5, 7]]

我想删除 t 中的子列表,例如[0,4],这两个数字已经存在于[0,4,5,7]中,我想保留较大的组并删除较小的组。所以最后 [[0, 4, 5, 7], [1,2,3,6]] 将是我的最终结果。

我试过下面的代码,但不知道哪里出了问题:

V=0
while V<60:
for o in t:
for p in t:
if o!= p:
for s in range(len(o)):
w=[]
if o[s] in p:
w.append(o[s])
#print w
if w==o:
t.remove(w)
V=V+1
print t

最佳答案

你可以为此使用集合:

lists = [[0, 4], [0, 4, 5, 7], [1, 2, 3, 6], [1, 3], [2, 6], [5, 7]]

sets = map(set, lists)
ret = []
for l in lists:
if not any(set(l) < s for s in sets):
ret.append(l)
print ret

在这里,set(l) < s检查列表 lproper subsets .

或者,如果你喜欢简洁:

sets = map(set, lists)
ret = [l for l in lists if not any(set(l) < s for s in sets)]
print ret

关于python - 从列表中删除一个子列表,其中数字已经存在于另一个子列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27796795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com