你可以使用
OrderedDict
来去重并保持顺序:
from collections import OrderedDict
inp= ['and', ['or', 'P', '-R', 'P'], ['or', '-Q', '-R', 'P']]
out = [OrderedDict.fromkeys(sub).keys() if isinstance(sub, list) else sub for sub in inp]
print(out)
['and', ['or', 'P', '-R'], ['or', '-Q', '-R', 'P']]
要删除重复的子列表,请将列表转换为元组,再次使用fromkeys:
inp = ['and', ['or', 'P', '-R', 'P'], ['or', '-Q', '-R', 'P'], ['or', 'P', '-R', 'P']]
out = OrderedDict.fromkeys(tuple(OrderedDict.fromkeys(sub).keys()) if isinstance(sub, list) else sub for sub in inp)
print(out.keys())
['and', ('or', 'P', '-R'), ('or', '-Q', '-R', 'P')]
如果您想再次使用列表,只需在Python2中进行转换并使用iterkeys:
out = OrderedDict.fromkeys(tuple(OrderedDict.fromkeys(sub).iterkeys()) if isinstance(sub, list) else sub for sub in inp)
print([list(ele) if isinstance(ele, tuple) else ele for ele in out.iterkeys()])