从列表中删除重复的子列表 [英] Remove duplicate sublists from a list

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

问题描述

如果我有一个这样的列表:

If I have a list like this one:

mylist = [[1,2,3], ['a', 'c'], [3,4,5],[1,2], [3,4,5], ['a', 'c'], [3,4,5], [1,2]]

删除重复子列表的最佳方法是什么?

What is best way to remove duplicate sub-lists?

现在我使用:

y, s = [ ], set( )
for t in mylist:
    w = tuple( sorted( t ) )
    if not w in s:
        y.append( t )
        s.add( w )

它有效,但是我想知道是否有更好的方法?还有一些类似python的东西吗?

It works, but I wonder if there is better way? Something more python-like?

推荐答案

将元素转换为元组*,然后将整个元素转换为集合,然后将所有内容转换回列表:

Convert the elements to a tuple*, then convert it the whole thing to a set, then convert everything back to a list:

m = [[1,2,3], ['a', 'c'], [3,4,5],[1,2], [3,4,5], ['a', 'c'], [3,4,5], [1,2]]

print [list(i) for i in set(map(tuple, m))]

*我们正在转换为元组,因为列表是不可散列的(因此我们不能在其上使用set

*we are converting to tuples because lists are non-hashable (and therefore we cannot use set on them

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

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