Каков наилучший способ создания всех возможных трех буквенных строк?
Я генерирую все возможные три буквы. e.g. aaa, aab, aac.... zzy, zzz
ниже - мой код:
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
keywords = []
for alpha1 in alphabets:
for alpha2 in alphabets:
for alpha3 in alphabets:
keywords.append(alpha1+alpha2+alpha3)
Может ли эта функциональность быть более гладкой и эффективной?
Ответы
Ответ 1
keywords = itertools.product(alphabets, repeat = 3)
См. документацию для itertools.product
. Если вам нужен список строк, просто используйте
keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 3)]
alphabets
также не обязательно должен быть списком, он может быть просто строкой, например:
from itertools import product
from string import ascii_lowercase
keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 3)]
будет работать, если вы просто хотите строчные буквы ascii.
Ответ 2
Вы также можете использовать карту вместо понимания списка (это один из случаев, когда карта еще быстрее, чем LC)
>>> from itertools import product
>>> from string import ascii_lowercase
>>> keywords = map(''.join, product(ascii_lowercase, repeat=3))
Этот вариант понимания списка также быстрее, чем использование ''.join
>>> keywords = [a+b+c for a,b,c in product(ascii_lowercase, repeat=3)]
Ответ 3
from itertools import combinations_with_replacement
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for (a,b,c) in combinations_with_replacement(alphabets, 3):
print a+b+c
Ответ 4
Вы также можете сделать это без каких-либо внешних модулей, выполнив простой расчет.
PermutationIterator
- это то, что вы ищете.
def permutation_atindex(_int, _set, length):
"""
Return the permutation at index '_int' for itemgetter '_set'
with length 'length'.
"""
items = []
strLength = len(_set)
index = _int % strLength
items.append(_set[index])
for n in xrange(1,length, 1):
_int //= strLength
index = _int % strLength
items.append(_set[index])
return items
class PermutationIterator:
"""
A class that can iterate over possible permuations
of the given 'iterable' and 'length' argument.
"""
def __init__(self, iterable, length):
self.length = length
self.current = 0
self.max = len(iterable) ** length
self.iterable = iterable
def __iter__(self):
return self
def __next__(self):
if self.current >= self.max:
raise StopIteration
try:
return permutation_atindex(self.current, self.iterable, self.length)
finally:
self.current += 1
Дайте ему итерируемый объект и целое число в качестве длины вывода.
from string import ascii_lowercase
for e in PermutationIterator(ascii_lowercase, 3):
print "".join(e)
Это начинается с 'aaa' и заканчивается на 'zzz'.
Ответ 5
chars = range(ord('a'), ord('z')+1);
print [chr(a) + chr(b) +chr(c) for a in chars for b in chars for c in chars]
Ответ 6
print([a+b+c for a in alphabets for b in alphabets for c in alphabets])