python - 检查 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 中使用列表等。
感谢您的帮助
解决方案
您正在循环遍历元素而不是索引
如果要使用索引:
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
推荐阅读
- javascript - React 无法读取组件上未定义的属性“映射”
- scala - Scala Cat 库验证列表按错误代码分组
- c# - Entity Framework Core 和 .NET Standard 2.0 - 不一致的行为
- c++ - 如何使用循环对所有数字求和?
- batch-file - 蝙蝠文件:使用变量搜索 .txt
- nestjs - 是否可以将参数传递给nestjs警卫?
- android - Android BottomSheet 展开到另一个视图的底部
- python - Python:如何检查字符串元素是否在字符串中并打印未包含的字符串元素?
- jenkins - 为什么 Jenkins Pipeline Artifactory 插件不向构建信息输出任何工件?
- python - 如何克服嵌套for循环以实现线性时间复杂度?