【问题标题】:How to remove duplicate lists in a list of list? [duplicate]如何删除列表列表中的重复列表? [复制]
【发布时间】:2012-08-30 13:51:28
【问题描述】:

我想从列表列表中删除所有重复列表。

所以我有一个这样的列表。

a = [[1,2],[1,2],[3,4,5],[3,4,5],[3,4,5]]

我想拥有:

b = [[1,2],[3,4,5]]

我不知道该怎么做。

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以使用一个集合:

    b_set = set(map(tuple,a))  #need to convert the inner lists to tuples so they are hashable
    b = map(list,b_set) #Now convert tuples back into lists (maybe unnecessary?)
    

    或者,如果您更喜欢列表推导式/生成器:

    b_set = set(tuple(x) for x in a)
    b = [ list(x) for x in b_set ]
    

    最后,如果顺序很重要,你总是可以排序 b:

    b.sort(key = lambda x: a.index(x) )
    

    【讨论】:

    • 如果您希望某样东西与众不同,那么套装就是您的最佳选择。 :)
    • lambda x: a.index(x) 可能只是 a.index
    • b = map(list,b_set) 将返回一个列表映射,如果您希望它返回到原始列表列表,您需要改为 b = list(map(list,b_set))
    【解决方案2】:

    如果列表的顺序不重要,请参阅 mgilson 的回答。如果您想保留订单,请执行以下操作:

    b = list()
    for sublist in a:
        if sublist not in b:
            b.append(sublist)
    

    这会将订单保留在原始列表中。但是,它比使用集合更慢且更冗长。

    【讨论】:

    • 也谢谢你,你的方法很有趣,但我不需要保持顺序。
    • 请注意,此方法将 [1,2] 和 [2,1] 视为不同,尽管它适用于本示例。
    • 这个方法很慢。避免使用追加
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 2014-07-14
    相关资源
    最近更新 更多