gpt4 book ai didi

python : Remove duplicate elements in lists and sublists; and remove full sublist if duplicate

转载 作者:行者123 更新时间:2023-11-28 21:51:52 36 4
gpt4 key购买 nike

是否有任何函数或方法可以在 python 2.7 中递归实现此目的?

Input : ['and', ['or', 'P', '-R', 'P'], ['or', '-Q', '-R', 'P']]
Output : ['and', ['or', 'P', '-R'], ['or', '-Q', '-R', 'P']]

删除 sublist1 中的重复“P”作为重复项

Input : ['and', ['or', 'P', '-R', 'P'], ['or', '-Q', '-R', 'P'], ['or', 'P', '-R', 'P']]
Output : ['and', ['or', 'P', '-R'], ['or', '-Q', '-R', 'P']]

删除子列表 1 中重复的“P”,并将子列表 3 作为子列表 1 的重复项删除

谢谢

最佳答案

我认为您必须创建自定义删除重复项 函数才能保留子列表的顺序。试试这个:

def rem_dup(lis):
y, s = [], set()
for t in lis:
w = tuple(sorted(t)) if isinstance(t, list) else t
if not w in s:
y.append(t)
s.add(w)
return y

inp = ['and', ['or', 'P', '-R', 'P'], ['or', '-Q', '-R', 'P'], ['or', 'P', '-R', 'P']]

out = [rem_dup(i) if isinstance(i, list) else i for i in rem_dup(inp)]

>>>out
['and', ['or', 'P', '-R'], ['or', '-Q', '-R', 'P']]

关于 python : Remove duplicate elements in lists and sublists; and remove full sublist if duplicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29179843/

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