Python 哪种方法更有效?
这段代码的目标是,用户将以任意顺序输入一个包含三个“通配符”符号的字符串。我在我的程序中赋予了一个意义(?是任何字母或数字,#是任何数字,&是任何字母)。然后,我想要一个适当字母和/或数字的每个组合的列表,但是它必须保持与原始通配符相同的顺序。最后,我将把所有这些新的组合替换回原来的字符串中Python 哪种方法更有效?,python,Python,这段代码的目标是,用户将以任意顺序输入一个包含三个“通配符”符号的字符串。我在我的程序中赋予了一个意义(?是任何字母或数字,#是任何数字,&是任何字母)。然后,我想要一个适当字母和/或数字的每个组合的列表,但是它必须保持与原始通配符相同的顺序。最后,我将把所有这些新的组合替换回原来的字符串中 wildcards = ['?', '#', '&'] #user has entered wildcards in this order n = len(wildcards) list = ite
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
wildcards=['?'、'#'、'&']#用户已按此顺序输入了通配符
n=len(通配符)
list=itertools.product('abc123',repeat=n)#创建每个字母和数字组合的笛卡尔乘积(目前仅使用abc123更易于管理)。
打印(列表)
对于列表中的x:#将遍历列表
iter=0
而iter
我觉得这应该可以做到,但必须有一种更有效的方法。我也遇到了这个错误。TypeError:“itertools.product”对象不支持项目删除,因此我无法删除不正确的列表项目。这是因为它是一个元组,我无法修改元组元素吗?您可以使用:
如果user\u 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的内置函数和数据类型是个好主意,例如
iter
和list
如果x[iter]!=string.digits正在做你认为应该做的事?@jDo谢谢,我会确保重命名它们。@padraic Cunningham,我正在尝试检查位于对象x中索引处的字符串是否不是数字,然后我们会做些什么,我错过了什么吗?谢谢如果x[iter]!=string.digits
正在检查如果x[iter]
等于“0123456789”,也许你的意思是如果不是x[iter].isdigit()
?哇,我想这正是我想要的……谢谢。你能给我介绍几个部分吗,因为我不太明白它是如何工作的。产品(*iterables)中的*做什么的。此外,我认为笛卡尔乘积有各种可能性,因此,如果用户字符串为“&&&&&”,您仍然会得到以数字开头的结果(这不是我想要的),但似乎不是这样!
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))