[英]Python - How to turn an IF statement into a Function to call multiple times with other strings?
我需要检查另一个变量中是否存在一个变量的排列,如果不存在,则增加一个计数器变量。
我设法创建了一个带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语句或计数器中的增量的输出?
我只是一个初学者,所以请通过本示例帮助我理解制作函数的概念。 我必须处理两个变量,其中一个循环遍历列表,而作为菜鸟,我不知道该怎么做。
PS我只是在学习,上面的代码只是一个试运行,因此请忽略每个if语句后面的打印功能。
你可以这样尝试
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.