我正在尝试研究如何将itertools.product传递给动态数量的参数。
我有以下代码按预期工作,打印出每行包含4个字符的行,顺序不同:
#!/usr/bin/env python3.5
import sys, itertools, multiprocessing, functools
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;"
num_parts = 4
part_size = len(alphabet) // num_parts
def do_job(first_bits):
for x in itertools.product(first_bits, alphabet, alphabet, alphabet):
print(''.join(x))
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=4)
results = []
for i in range(num_parts):
if i == num_parts - 1:
first_bit = alphabet[part_size * i :]
else:
first_bit = alphabet[part_size * i : part_size * (i+1)]
pool.apply_async(do_job, (first_bit,))
pool.close()
pool.join()
然后我尝试使用以下代码使其完全动态化,其中基于num_parts变量动态创建字母数据参数:
#!/usr/bin/env python3.5
import sys, itertools, multiprocessing, functools
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;"
num_parts = 4
part_size = len(alphabet) // num_parts
dynamicArgs = []
def do_job(first_bits):
for x in itertools.product(first_bits, *dynamicArgs):
print(''.join(x))
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=4)
results = []
for x in range(num_parts-1):
dynamicArgs.append(alphabet)
for i in range(num_parts):
if i == num_parts - 1:
first_bit = alphabet[part_size * i :]
else:
first_bit = alphabet[part_size * i : part_size * (i+1)]
pool.apply_async(do_job, (first_bit,))
pool.close()
pool.join()
但这不能按预期工作......它在每一行输出一行字符,并且只在字母表上迭代一次。
如何将动态数量的字母变量作为参数传递给itertools.product?
感谢您的时间。
答案 0 :(得分:1)
您可以将字符串列表相乘:
def do_job(first_bits):
for x in itertools.product(first_bits, *[alphabet] * 3):
您也可以使用 itertools.repeat :
from itertools import repeat
def do_job(first_bits, times):
for x in itertools.product(first_bits, *repeat(alphabet, times)):
答案 1 :(得分:0)
这是你想要做的吗?
import sys, itertools, multiprocessing, functools
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;"
repeats = 5
alphabets = [ alphabet ] * repeats
def do_job(first_bits):
for x in itertools.product(first_bits, *alphabets):
print(''.join(x))
do_job('12345')
您可以在重复元素的数组上使用*
运算符。
输出:
1aaaaa
1aaaab
1aaaac
1aaaad
1aaaae
1aaaaf
1aaaag
1aaaah
1aaaai
1aaaaj
1aaaak
[...]