首页 > 解决方案 > 在python中使用某些参数进行所有组合

问题描述

所以我试图制作一个可以制作所有组合然后打印它的东西,用这个

import random
import string


def randomString(stringLength=3):
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(stringLength))

print(randomString(3)+str(random.randint(10, 99))+(randomString(3)))

但我无法让它工作......我希望它看起来像这样,所以它打印所有组合。aaa00aaa aaa00aab aaa00aac aaa00aad

等等

标签: python

解决方案


要制作所有可能的字母组合,您可以使用product()formitertools

from itertools import product
import string
letters = string.ascii_lowercase
# repeat here sets the length of how many letters you want
all_combinations = product(letters, repeat=3)
new_arr = [''.join(x) for x in all_combinations]
# this new_arr will be an array of strings of all combinations

对我来说,您似乎不想获得随机整数,而是想要某个模式之王的增量数。 打印随机整数

# continuing upper code
import random
# to print the patter you want you can use F-string if you have python 3.6 and up
# or you can use format()
# You also need loops two loops to print your strings
for first_part in new_arr:
    for second_part in new_arr:
        print(f"{first_part}{random.randint(0, 99)}{secondPart}") #using F-String
        print("{}{}{}".format(first_part, random.randint(0, 99), secondPart)) # using format

# If you want to increment numbers and reset and start from 0 again
# Basically you need the same thing with a few changes
# first use a variable that will change
i = 0
for first_part in new_arr:
    for second_part in new_arr:
        print(f"{first_part}{i}{secondPart}") #using F-String
        print("{}{}{}".format(first_part, i, secondPart)) # using format
        i += 1 #increment variable by one
        if i == 100:
            i = 0 #reset i back to 0

请记住,这只会将 0 - 9 作为一个字符打印例如:aaa0aaa 而不是 aaa00aaa


推荐阅读