Skip to main content
 首页 » 编程设计

python之创建一个 python 集合/唯一列表

2025年05月04日24JeffreyZhao

我正在尝试使用 set 获取唯一列表,但我的循环方法显示了所有可能性并重复了一些已经存在的列表成员 - 它只是交换它们。我在想也许我应该使用字典 - 只需将一个成员设为常量并避免执行当前循环方法。

尝试过:

a=['hello','mam','dictionary','why','lives','elvis','hey','indicatory'] 
x = 1 
while x < len(a): 
    for i in a: 
        if signature(a[x]) == signature(i) and a[x] != i: 
            anagram=print([a[x],i],end =' ') 
    x += 1 
 
print(set(anagram)) 

出现错误:

IndexError: list index out of range

我遇到问题的代码:

def signature(word): 
    return ''.join(sorted(word)) 
 
a=['hello','mam','dictionary','why','lives','elvis','hey','indicatory'] 
 
x = 1 
unique_list = [] 
while x < 8: 
    for i in a: 
        if signature(a[x]) == signature(i) and a[x] != i: 
            y = (a[x], i) 
            unique_list.append(y)                                             
    x += 1 
 
print(list(set(unique_list))) 

实际结果: [('lives', 'elvis'), ('elvis', 'lives'), ('indicatory', 'dictionary'), ('dictionary', 'indicatory')]

预期结果: [('lives', 'elvis'), ('indicatory', 'dictionary')]

请您参考如下方法:

考虑使用 defaultdict .然后你可以做

from collections import defaultdict 
d = defaultdict(list) 
a = ['hello','mam','dictionary','why','lives','elvis','hey','indicatory'] 
for i in a: 
    d[''.join(sorted(i))].append(i) 
out = [tuple(i) for i in d.values() if len(i) > 1] 
print(out) 

打印

[('dictionary', 'indicatory'), ('lives', 'elvis')]