【问题标题】:Python - remove list duplicates that are in reverse orderPython - 删除以相反顺序排列的重复列表
【发布时间】:2018-10-13 13:02:12
【问题描述】:

关于解决我在 Python 中遇到的问题的任何想法...

我有一个嵌套列表,其中包含重复但顺序相反的项目(顺序保持不变,但它们在中间切换):

links = [['a', 'b', 'c', 'd'], ['c', 'd', 'a', 'b'], ['e', 'f', 'g', 'h'], ['g', 'h', 'e', 'f']]

是否有人对删除重复项的最佳方法有建议,所以我最终得到:

links = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]

我想检测重复项并将其删除,第一个实例需要保持完全相同且顺序相同,因此在上面的示例中,我要删除列表项 1 (['c', 'd', 'a', 'b']) 和 3(['g', 'h', 'e', 'f'])

提前致谢!

【问题讨论】:

  • 请展示您的编码尝试
  • ['h', 'g', 'f', 'e'] 是否也会出现,是否必须单独考虑?

标签: python


【解决方案1】:

与其他响应类似,但保持原始列表的顺序。

def get_uniques(links):    
    my_set = set([])
    my_selection = []
    for l in links:
        s = "".join(sorted(l))
        if not s in my_set:
            my_set.add(s)
            my_selection.append(l)
    return my_selection

还有一个神秘的单线式(可能更有效):

scheck = set()
survivers = [ (l, scheck.add("".join(sorted(l))) ) 
                         for l in links if  not "".join(sorted(l)) in scheck ]
result = [a for a, _ in survivers]

【讨论】:

  • Eguaio,非常感谢您的解决方案!这让我有一段时间摸不着头脑!我觉得套装是要走的路,但我不确定到底是怎么回事!谢谢!
  • 很高兴听到这个消息!可以使用字典编写等效的解决方案。可以使用列表代替集合,但一个重要方面是集合元素(以及字典键)是散列的,因此“if s in myset”检查是在恒定时间内完成的。如果它是一个列表,时间将是线性的。这是在这里使用集合(或字典)的真正好处。
【解决方案2】:

您可以先对列表中的所有项目进行排序并转换为字符串:

l = [ "".join(sorted(l)) for l in links ]

转换允许您使用保证没有重复的“设置”:

l = list(set(l))

最后,将字符串转换回字符列表:

l = [ list(l) for l in l ]

【讨论】:

  • 我会注意到这种方法不是保序的。
【解决方案3】:

先对list的元素进行排序,然后删除重复项。 找到我的代码,listfinal 代表你的答案。

links = [['a', 'b', 'c', 'd'], ['c', 'd', 'a', 'b'], ['e', 'f', 'g', 'h'], 

['g', 'h', 'e', 'f']]
links1=[]
for elements in links:
    elements=sorted(elements)
    links1.append(elements)
# print links1
linksfinal=[list(t) for t in set(tuple(element) for element in links1)]
print linksfinal

【讨论】:

  • 这也不是保序的。
猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多