我需要检查另一个变量中是否存在一个变量的排列,如果不存在,则增加一个计数器变量。
我设法创建了一个带for循环的条件语句,以列出所需的排列并检查变量是否存在。我需要将其变成一个函数,以便我可以使代码更整洁,因为我需要该函数来检查多个变量之间的多个变量。
charList = ['A', 'B', 'C'] #actual code has other items in this list
name = "JOHN" #actual variable whose permutations are to be made for checking
checkName = "JOAN" #target variable to check against the permutations of above variable
counter = 0
if checkName is name:
print('found1')
elif checkName in (name[:i] + c + name[i + 1:] for i in range(len(name)) for c in charList):
print('found2')
elif checkName in ([name[:i] + c + name[i:] for i in range(len(name)) for c in charList]):
print('found3')
elif checkName in ([name[0:i] + name[i+1] + name[i] + name[i+2:] for i in range(len(name) - 1)]):
print('found4')
else:
counter += 1
print(counter)
如何使其成为函数,以便仅通过使用另一个名称变量就可以直接获得print语句或计数器中的增量的输出?
我只是一个初学者,所以请通过本示例帮助我理解制作函数的概念。我必须处理两个变量,其中一个循环遍历列表,而作为菜鸟,我不知道该怎么做。
P.S。我只是在学习,上面的代码只是试运行,所以请忽略每个if语句后面的打印功能。
答案 0 :(得分:2)
您可以尝试这样
charList = ['A', 'B', 'C'] #actual code has other items in this list
name = "JOHN" #actual variable whose permutations are to be made for checking
checkName = "JOAN" #target variable to check against the permutations of above variable
def checkName_fun(checkName, name):
counter = 0
if checkName is name:
return ('found1')
elif checkName in (name[:i] + c + name[i + 1:] for i in range(len(name)) for c in charList):
return ('found2')
elif checkName in ([name[:i] + c + name[i:] for i in range(len(name)) for c in charList]):
return ('found3')
elif checkName in ([name[0:i] + name[i+1] + name[i] + name[i+2:] for i in range(len(name) - 1)]):
return ('found4')
else:
counter += 1
return (counter)
checkName_fun(checkName, name)