gpt4 book ai didi

Python - 如何将 IF 语句转换为函数以使用其他字符串多次调用?

转载 作者:行者123 更新时间:2023-12-01 00:50:00 25 4
gpt4 key购买 nike

我需要检查一个变量的排列是否存在于另一个变量中,如果不存在则递增计数器变量。

我已经成功创建了一个带有 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)

如何将其变成一个函数,以便仅通过使用另一个名称变量就可以直接获得打印语句或计数器增量的输出?

我只是一个初学者,所以请通过这个例子帮助我理解创建函数的概念。我必须处理两个变量,其中一个变量循环遍历列表,作为菜鸟,我不知道该怎么做。

附注我刚刚学习,上面的代码只是一个试运行,所以请忽略每个 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)

关于Python - 如何将 IF 语句转换为函数以使用其他字符串多次调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56641618/

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