在python中使用某些参数进行所有组合

2024-09-30 03:25:20 发布

您现在位置: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

等等


Tags: inimportforstringreturndefasciirange
1条回答
网友
1楼 · 发布于 2024-09-30 03:25:20

要生成所有可能的字母组合,可以使用product()表单itertools

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

相关问题 更多 >

    热门问题