简体   繁体   中英

How to get that output from a generic list in python

is there a way to get this output:

a
b
aa
ab
ba
bb
aaa
aab...

using a list like this:

List = ["a","b"]

the method below can't be used because the output should be infinite

for i in List:
   print(i)
for i in List:
   for k in List:
      print (i+k)
for i in List:
   for k in List:
      for j in List:
         print(i+k+j)
#etc.

You could define a generator function using itertools.product :

>>> import itertools
>>> def infinite_products(chars):
...     for repeat in itertools.count(1):
...         for result in itertools.product(chars, repeat=repeat):
...             yield ''.join(result)
...
>>> for result in infinite_products("ab"):
...     print(result)
...
a
b
aa
ab
ba
bb
aaa
aab
aba
abb
baa
bab
bba
bbb
aaaa
aaab
aaba
aabb
abaa
abab
abba
abbb
baaa
baab
baba
babb
bbaa
bbab
bbba
bbbb
aaaaa
aaaab
aaaba
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM