删除子列表重复项,包括反转 [英] Remove sublist duplicates including reversed

查看:50
本文介绍了删除子列表重复项,包括反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有以下

list = [['1', '2'], ['1', '3'], ['1', '4'], ['1', '5'], ['2', '1'], ['4', '1'], ['2', '6']]

如果子列表在同一个列表中有反向子列表(即 ['1', '2'] = ['2', '1']) ,我想匹配,如果为 True 则从列出镜像的.

I want to match if a sub list has a reversed sub list within same list (i.e. ['1', '2'] = ['2', '1']) , and if True than to remove from the list the mirrored one.

最终列表应如下所示:

list = [['1', '2'], ['1', '3'], ['1', '4'], ['1', '5']['2', '6']]

这是我试过的:

for i in range(len(list)):
    if list[i] == list[i][::-1]:
            print("Match found")
            del list[i][::-1]

print(list)

但最终我得到了与原始列表相同的列表.我不确定我的匹配条件是否正确.

But finally I get the same list as original. I am not sure if my matching condition is correct.

推荐答案

您可以遍历列表的元素,并使用 set 以跟踪目前已看到的那些.使用集合是检查成员资格的更方便的方法,因为操作 具有较低的复杂性,在这种情况下,您需要使用元组,因为列表不可散列.然后,如果没有看到实际的元组或 reversed ,则保留这些项目(如果您只想忽略那些具有 reversed 的项目,您只需要 if tuple(reversed(t)) in s):

You could iterate over the elements of the list, and use a set to keep track of those that have been seen so far. Using a set is a more convenient way to check for membership, since the operation has a lower complexity, and in that case you'll need to work with tuples, since lists aren't hashable. Then just keep those items if neither the actual tuple or the reversed have been seen (if you just want to ignore those which have a reversed you just need if tuple(reversed(t)) in s):

s = set()
out = []
for i in l:
    t = tuple(i)
    if t in s or tuple(reversed(t)) in s:
        continue
    s.add(t)
    out.append(i)


print(out)
# [['1', '2'], ['1', '3'], ['1', '4'], ['1', '5'], ['2', '6']]

这篇关于删除子列表重复项,包括反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆