检查Python列表是否包含特定元素

时间:2020-02-10 10:47:44

标签: python list

我编写了一个示例程序来根据输入生成哈希码(尚未完成,因此您看不到它实际生成哈希的部分):

import hashlib

def isInputValid(input, validInput=[]):
    for i in validInput:
        if validInput[i] == input: # error generated here
            return True
            pass
        i = i + 1
    return False
    pass

sha1hash = hashlib.sha1()
choiceValidInputs = ["1", "2"]

print ("Welcome to hash generator!\n")
print ("[1] -- generate hash from input")
print ("[2] -- quit")
choice = input("\nWhat do you want to do? ")
if not isInputValid(choice, choiceValidInputs):
    print ("Invalid option; try again")
    choice = input("What do you want to do? ")

if choice == "1":
    print ("\n[1] SHA1/SHA256")
    print ("[2] SHA512")
    hashType = input("\nWhat hash type do you want? ")
    ...
elif choice == "2":
    print ("Goodbye!")
    quit()

我的终端窗口:

kali@kali:~$ python3 /home/bin/hashgenerator.py 
Welcome to hash generator!

[1] -- generate hash from input
[2] -- quit

What do you want to do? 1
Traceback (most recent call last):
  File "/home/bin/hashgenerator.py", line 19, in <module>
    if isInputValid(choice, choiceInput)==False:
  File "/home/bin/hashgenerator.py", line 5, in isInputValid
    if validInput[i] == input:
TypeError: list indices must be integers or slices, not str
kali@kali:~$ 

我想检查输入内容是否在choiceValidInputs中。我实际上并不真正知道如何在Python中使用列表等。

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

您正在遍历元素而不是索引

如果要使用索引:

def isInputValid(input, validInput=[]):
    for i in range(len(validInput)):
        if validInput[i] == input: # error generated here
            return True

如果您想使用元素,可以做到

def isInputValid(input, validInput=[]):
    for i in validInput:
        if i == input: # error generated here
            return True

但是您可以更轻松地做到这一点。而且更正确:)

def isInputValid(input, validInput=[]):
    return input in validInput

答案 1 :(得分:1)

for i in validInput:
    if validInput[i] == input:

ivalidInput中不是项目的索引,它是项目本身。您想做的是:

for i in validInput:
    if i == input:

此外,您不需要下面的passi = i+1。而且我建议将变量input重命名为其他名称,以避免与input()函数混淆。