首页 > 解决方案 > 检查 Python 列表是否包含特定元素

问题描述

我编写了一个示例程序来从输入生成哈希码(它还没有完成,所以你看不到它实际生成哈希的部分):

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 中使用列表等。

感谢您的帮助

标签: pythonlist

解决方案


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

如果要使用索引:

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

推荐阅读