gpt4 book ai didi

python - 什么是更有效的方法来做到这一点?

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:01 25 4
gpt4 key购买 nike

此代码的目标是用户将按任意顺序输入包含三个“通配符”符号的字符串。我已经在程序中指定了一个含义(?是任何字母或数字,# 是任何数字,& 是任何字母)。然后,我想要一个包含适当字母和/或数字的每种组合的列表,但它必须保持与原始通配符相同的顺序。最终我会将所有这些新组合替换回原始字符串。

wildcards = ['?', '#', '&'] #user has entered wildcards in this order
n = len(wildcards)
list = itertools.product('abc123',repeat=n) #creates a cartesian product of every combination of letters and numbers (only using abc123 to be more manageable for now.
print(list)
for x in list: #going to iterate through the list
iter = 0
while iter < n: #iterating through an individual object in the list
if wildcards[iter] == '#': #if that index should be a number but isn't, we delete that object from the list
if x[iter] != string.digits:
del list[x]
elif wildcards[iter] == '&': #if it should be a letter and isn't we delete the object
if x[iter] != string.ascii_lowercase:
del list[x]
iter = iter+1
print(list) #print the new list

我觉得这应该可行,但必须有一种更有效的方法来做到这一点。我也遇到这个错误。 TypeError: 'itertools.product' 对象不支持项目删除,因此我无法删除不正确的列表项目。是因为它是一个元组而我无法修改元组元素吗?

最佳答案

您可以使用itertools.product :

import itertools
import string

user_string = '???'
iterables = []
for c in user_string:
if c == '?':
iterables.append(string.ascii_lowercase + string.digits)
elif c == '&':
iterables.append(string.ascii_lowercase)
elif c == '#':
iterables.append(string.digits)

for item in itertools.product(*iterables):
print(''.join(item))

如果 user_string 包含通配符以外的字符,您也可以执行此操作:

import itertools
import string

user_string = 'aaa???'
iterables = []
for c in user_string:
if c == '?':
iterables.append(string.ascii_lowercase + string.digits)
elif c == '&':
iterables.append(string.ascii_lowercase)
elif c == '#':
iterables.append(string.digits)
else:
iterables.append([c])

for item in itertools.product(*iterables):
print(''.join(item))

关于python - 什么是更有效的方法来做到这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36392135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com