在Python中过滤数组中的Anagram

2024-05-13 22:21:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遍历一个数组并删除python中不是anagram的元素。这是我写的代码。我的逻辑似乎很好,但我似乎搞不懂。在

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

Tags: 代码元素for数组逻辑arrayactcat
3条回答

对现有代码进行一些小的调整就可以了。在

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']

程序中的第一个问题是,您正在for循环外初始化t到{},因此您只检查{}的第一个元素和所有元素,对于{}循环的其余迭代,t总是大于len(b),因此它永远不会进入内部循环,从for循环的第二次迭代开始。一个简单的解决办法-

for i in b:
    t = 0
    while t<len(b):
        if ''.join(sorted(i))==''.join(sorted(b[t])):
           array.append(i)
        t+=1

但是对于寻找字谜,我认为你过于复杂化了,你可以简单地找出字符串字符的ASCII值之和,然后将其与其他相同的和和和长度进行比较,然后检查ASCII值和字符串长度是否匹配,如果匹配,则它们就是anagram。在

此方法的示例代码-

^{pr2}$

另一种方法

使用itertools groupby

In [18]: from itertools import groupby


In [19]: c=[list(g) for k,g in groupby(sorted(b,key=sorted),sorted)]

In [20]: c
Out[20]: [['cat', 'act'], ['lap'], ['star'], ['dog', 'god']]

In [21]: [x for _list in c if len(_list)>1 for x in _list]
Out[21]: ['cat', 'act', 'dog', 'god']

The key thing here is to use itertools.groupby from the itertools module which will group items in a list together.

The list we supply to groupby has to be sorted in advanced so we pass it sorted(b,key=sorted). The trick here is that sorted can take a key function and will sort based on the output from this function, so we pass sorted again as the key function and this will will sort the words using the letters of the string in order. There's no need to define our own function or create a lambda.

groupby takes a key function which it uses to tell if items should be grouped together and again we can just pass it the built-in sorted function.

来源:Finding and grouping anagrams by Python

相关问题 更多 >