簡體   English   中英

Python-如何將IF語句轉換為函數以與其他字符串多次調用?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM