首页 > 解决方案 > 有没有办法返回在 any() 函数中返回 True 的元素的索引?

问题描述

(这只是我想要解决的一个例子)

array = ["hello", "hi"]

statement = input()

condition = any(statement in elm for elm in array)

有没有办法返回返回 True 的元素的索引,或者我应该只使用 for 循环?

标签: pythonpython-3.xlistany

解决方案


事实上你想要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

推荐阅读