zz $ m $ b for y in m_from_n([0,1],3): print y [0,0,0] [0,0,1] [0,1,0] [ 0,1,1] [1,0,0] [1,0,1] [1,1,0] ] [1,1,1] $ m $ b for y in m_from_n(" abcdefghijklmnopqrstuvwxyz",4): 打印''''。join(y) 应该或多或少地做你想做的事。 Charles s =" abcd" def a(n): 如果n = = 0: 收益'''' 返回 for c in s: for r in a (n-1): 收益率c + r 打印列表(a(3)) Hi all.I want to create a large list like:aaaa ~ zzzzIs there any good algorithm to do this?ThanxJia Lu 解决方案Sure.test = ''01''for m in test:for n in test:for o in test:for p in test:print m+n+o+p## 0000## 0001## 0010## 0011## 0100## 0101## 0110## 0111## 1000## 1001## 1010## 1011## 1100## 1101## 1110## 1111Now just change test=''01'' to test=''abcdefghijklmnopqrstuvwxyz''.Sure.test = ''01''for m in test: for n in test: for o in test: for p in test: print m+n+o+p[snip]Forgive any silly mistakes I have made (I''ve been teachingmyself python for about 1 week) but there is a moderatelywell known algorithm for this that extends to arbitrarylengths of both the list of alternatives and the lengthof the required output, and avoids deeply nested loops.I know that it is no better for small and constant outputlengths, but for longer lengths or if the output lengthcan vary it should be better. There is a similar algorithmif duplicates are not allowed (ie abcd ... wxyz).My attempt at a python translation of the algorithm:def m_from_n ( v, m ):"""Print all combinations of m things from v[0] ... v[n-1],duplicates OK. Yields a list."""x = [0] * mwhile True:yield [ v[i] for i in x ]i = m - 1while i>=0 and x[i]==len(v)-1:x[i] = 0i = i - 1if i >= 0:x[i] = x[i] + 1else:returnfor y in m_from_n( "xyz", 2 ):print ''''.join(y)xxxyxzyxyyyzzxzyzzfor y in m_from_n( [0,1], 3 ):print y[0, 0, 0][0, 0, 1][0, 1, 0][0, 1, 1][1, 0, 0][1, 0, 1][1, 1, 0][1, 1, 1]for y in m_from_n( "abcdefghijklmnopqrstuvwxyz", 4 ):print ''''.join(y)should more or less do what you want.Charless = "abcd"def a(n):if n==0:yield ''''returnfor c in s:for r in a(n-1):yield c+rprint list(a(3)) 这篇关于算法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!