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']
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.
对现有代码进行一些小的调整就可以了。在
程序中的第一个问题是,您正在for循环外初始化},因此您只检查{}的第一个元素和所有元素,对于{}循环的其余迭代,t总是大于len(b),因此它永远不会进入内部循环,从
t
到{for
循环的第二次迭代开始。一个简单的解决办法-但是对于寻找字谜,我认为你过于复杂化了,你可以简单地找出字符串字符的ASCII值之和,然后将其与其他相同的和和和长度进行比较,然后检查ASCII值和字符串长度是否匹配,如果匹配,则它们就是anagram。在
此方法的示例代码-
^{pr2}$另一种方法
使用itertools groupby
来源:Finding and grouping anagrams by Python
相关问题 更多 >
编程相关推荐