Skip to main content
 首页 » 编程设计

python之在 Python 中过滤数组中的 Anagram

2025年05月04日12sky-heaven

我正在尝试遍历一个数组并删除不是 python 中的变位词的元素。这是我写的代码。我的逻辑似乎很好,但我似乎无法理解。

b = ['cat', 'dog', 'god', 'star', 'lap', 'act'] 
array=[] 
t=0 
for i in b: 
    while t<len(b): 
        if ''.join(sorted(i))==''.join(sorted(b[t])): 
           array.append(i) 
        t+=1 
print array 

请您参考如下方法:

只需对现有代码进行一些小的调整即可。

b = ['cat', 'dog', 'god', 'star', 'lap', 'act'] 
array = [] 
t = 0 
for i, value in enumerate(b): 
    t = i+1 
    while t<len(b): 
        if ''.join(sorted(value))==''.join(sorted(b[t])): 
            array.extend([value, b[t]]) 
        t+=1 
print array 
['cat', 'act', 'dog', 'god']