从具有不可散列元素的列表中取出唯一值

时间:2019-03-02 23:47:04

标签: python python-3.x

所以我有以下列表:

test_list = ['Hallo', 42, [1, 2], 42, 3 + 2j, 'Hallo', 'Hello', [1, 2], [2, 3], 3 + 2j, 42] 

现在,我想从列表中获取唯一值并将其打印在屏幕上。我尝试使用set函数,但是(类型错误:不可使用的类型:'list')不起作用,因为其中的[1,2]和[2,3]值名单。我尝试使用append和extend函数,但是还没有提出解决方案。

期望:       ['Hallo',42,[1,2],(3 + 2j),'Hello',[2,3]]

def unique_list(a_list): 
    a = set(a_list)
    print(a)
a_list = ['Hallo', 42, [1, 2], 42, 3 + 2j, 'Hallo', 'Hello', [1, 2], [2, 3], 3 + 2j, 42]
print(unique_list(a_list))   

5 个答案:

答案 0 :(得分:1)

您可以使用一个简单的for循环,该循环仅附加新元素:

test_list = ['Hallo', 42, [1, 2], 42, 3 + 2j, 'Hallo', 'Hello', [1, 2], [2, 3], 3 + 2j, 42]
new_list = []

for item in test_list:
    if item not in new_list:
        new_list.append(item)

print(new_list)
# ['Hallo', 42, [1, 2], (3+2j), 'Hello', [2, 3]]

答案 1 :(得分:1)

如果列表包含不可散列的元素,请使用repr创建可散列的键,该键可与集合一起使用:

def unique_list(a_list):
    seen = set()
    for x in a_list:
        key = repr(x)
        if key not in seen:
            seen.add(key)
            print(x)

答案 2 :(得分:0)

您可以在O(n ^ 2)中运行的常规for循环中完成此操作。

def unique_list(a_list):
    orig = a_list[:]               # shallow-copy original list to avoid modifying it
    uniq = []                      # start with an empty list as our result
    while(len(orig) > 0):          # iterate through the original list
        uniq.append(orig[0])       # for each element, append it to the unique elements list
        while(uniq[-1] in orig):   # then, remove all occurrences of that element in the original list
            orig.remove(uniq[-1])
    return uniq                    # finally, return the list of unique elements in order of first occurrence in the original list

也许还有一种方法可以将其添加到列表理解中,这会更加优雅,但是目前我无法弄清楚。如果每个元素都是可哈希的,则可以使用set方法,这会更容易。

答案 3 :(得分:0)

一种可以在线性时间内解决此问题的方法是使用诸如pickle之类的序列化程序对项目进行序列化,以便可以将诸如列表之类的不可散列对象添加到集合中以进行重复数据删除,但是由于集合在Python和您显然希望输出以原始插入顺序显示,则可以使用dict.fromkeys代替:

import pickle
list(map(pickle.loads, dict.fromkeys(map(pickle.dumps, test_list))))

因此,给定您的示例输入,将返回:

['Hallo', 42, [1, 2], (3+2j), 'Hello', [2, 3]]

请注意,如果您使用的Python 3.6或更早版本不能保证字典的关键顺序,则可以使用collections.OrderedDict代替dict

答案 4 :(得分:0)

要从非哈希表中获取唯一项,可以按等价方式进行分区,这是一种二次方方法,因为它将每个项与每个分区中的项进行比较,如果不等于其中一个会为该项目创建一个新分区,然后获取每个分区的第一项。

如果某些项目是可哈希的,则可以将等价项的划分限制为仅不可哈希。然后将其余的物品喂入一组。

import itertools

def partition(L):
    parts = []
    for item in L:
        for part in parts:
            if item == part[0]:
               part.append(item)
               break
        else:
            parts.append([item])
    return parts

def unique(L):
    return [p[0] for p in partition(L)]

未经测试。