python - 有没有办法返回在 any() 函数中返回 True 的元素的索引?
问题描述
(这只是我想要解决的一个例子)
array = ["hello", "hi"]
statement = input()
condition = any(statement in elm for elm in array)
有没有办法返回返回 True 的元素的索引,或者我应该只使用 for 循环?
解决方案
事实上你想要index
的声明array
array = ["hello", "hi"]
statement = input("Give a word: ")
condition = array.index(statement) if statement in array else -1
print(condition)
演示
Give a word: hello
0
Give a word: hi
1
Give a word: Hi
-1
推荐阅读
- machine-learning - 我的线性回归梯度下降不会收敛
- python - 尝试为我的 python 实验室使用总收益等式时出现问题
- python-3.x - python中的print('')和print('')有什么区别?
- reactjs - Reactjs this.props.map 不是函数
- php - 出现错误 SQLSTATE[HY000]:一般错误:尝试执行 if 语句时出现 2031
- javascript - 如何在 Vanilla JS 中使用 Firebase Polyfill
- python - 如何在 Python 中分离日志处理程序
- qt - mingw 交叉编译器不会静态链接 qt 库
- ios - 动态更改 iOS 导航栏颜色(深色模式)
- android - 任务':react-native-interactable:compileDebugJavaWithJavac'的本机反应失败