2016-10-31 101 views
1

我想檢查通過函數中的參數給出的字符串是否在列表中。代碼本身不會產生任何錯誤,但它的工作方式是錯誤的。如果我給我的函數「-a」作爲參數,它仍然說它不在列表中,但它肯定是。檢查列表中的元素

這是代碼:

def generatePassword(pLength, mode): 
    password = str() 
    commands = ["-a", "-n", "-s", "-allupper", "-mixupper"] 
    alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", 
       "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] 
    specialCharacters = ["!", "?", "&", "@", 
         "-", "=", "#", "+", "*", "/", "%", "§"] 
    if mode.lower().split() not in commands: 
     print("Couldn't recognize commands...") 
    else: 
     for n in range(pLength): 
      i = random.randint(1, 2) 
      if "-a" in mode.lower().split(): 
       password += alphabet[random.randint(0, 25)] 
     print("[+]", password) 

generatePassword(30, "-a") 
+1

你的第一個'if'行詢問是否名單是在另一個列表中,即使列表相同,對於非嵌套列表,這也不會成立。 –

+0

當您分割字符串時,輸出將是一個列表。由於該列表不存在於'commands'中,它正在返回'False'。放下'split()'來解決這個問題。 – thefourtheye

+0

@thefourtheye僅僅丟掉'spilled()'不是一個解決方案。可能不僅僅是命令。 – Psytho

回答

0

可以使用any命令來檢查是否有任何的mode.lower().split()詞語的不命令:

def generatePassword(pLength, mode): 
    password = str() 
    commands = ["-a", "-n", "-s", "-allupper", "-mixupper"] 
    alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", 
       "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] 
    specialCharacters = ["!", "?", "&", "@", 
         "-", "=", "#", "+", "*", "/", "%", "§"] 

    if any(x not in commands for x in mode.lower().split()): 
     print("Couldn't recognize commands...") 
    else: 
     for n in range(pLength): 
      i = random.randint(1, 2) 
      if "-a" in mode.lower().split(): 
       password += alphabet[random.randint(0, 25)] 
     print("[+]", password) 

generatePassword(30, "-a") 
+0

這樣,它不會讓我在參數中使用多個命令。這就是爲什麼我將它分開:/ – hudumudu

+0

@hudumudu現在查看答案!您可以使用'any'命令查看'mode.lower()。split()'中的任何單詞是否不在命令中。 – gowrath

+0

這工作以及謝謝!我可以在Stackoverflow中正確接受多個答案嗎? – hudumudu

-1

變化

mode.lower().split() 

mode.lower() 
2

你的情況很不好:

if mode.lower().split() not in commands: 
    print("Couldn't recognize commands...") 

通過(例如)替換它:

args = set(mode.lower().split()) 
if not set(args).issubset(set(commands)): 
    print("Couldn't recognize commands...") 

http://python.6.x6.nabble.com/Test-if-list-contains-another-list-td1506964.html

+0

這對我工作謝謝!我還沒有學習套件,因此我不知道何時以及如何實現它們,但我很快就會看看它們。 – hudumudu