如何清除列表列表中的冗余值

时间:2014-04-06 23:47:57

标签: python sublist

说我有一份清单 X=[[0,0,0,3,4],[8,8,9,2,8,2]]

如何制作,以便每个子列表只包含一次重复的数字:
喜欢这个新列表:

XNew=[[0,3,4],[8,9,2]]

2 个答案:

答案 0 :(得分:5)

您可以使用set

new_x = [list(set(i)) for i in old_x]

集合是唯一元素的集合,因此当将重复值列表转换为集合时,会创建一组唯一值。然后,您可以将该集转换回列表并获得所需的结果。

实施例

>>> old_x = [[0,0,0,3,4],[8,8,9,2,8,2]]
>>> new_x = [list(set(i)) for i in old_x]
>>> print new_x
[[0,3,4],[8,9,2]]

答案 1 :(得分:0)

如果您需要保留数字的顺序,则无法使用集合。这将保留原始顺序:

lst = [[0, 0, 0, 3, 4], [8, 8, 9, 2, 8, 2]]
new_lst = []

for sub_lst in lst:
    seen = set()
    new_sub = []
    for item in sub_lst:
        if item not in seen:
            new_sub.append(item)
            seen.add(item)
    new_lst.append(new_sub)

print new_lst # [[0, 3, 4], [8, 9, 2]]