python - 在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
等等
解决方案
要制作所有可能的字母组合,您可以使用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
推荐阅读
- machine-learning - 在 AWS SageMaker 上使用 H2O.ai H2O-3 Automl 算法进行分类:分类列
- node.js - 使用 Material-UI 样式时反应钩子错误
- python - 弹出命令提示符奇怪的行为
- intellij-idea - Intellisense - 通过其方法推断正确的类
- image - 我如何读取这个文件的用户数据
- javascript - 即使单击具有 stopPropagation 的元素,也隐藏所有单击事件上的元素
- rxjs - 逻辑或组合 2 个或更多可观察流
- html - autocomplete=off 不适用于谷歌浏览器
- apache-spark - spark2-submit 抛出多个包的错误(--packages)
- math - 如何计算 3D 中点的偏航、俯仰和滚动?