有没有办法 return 在 any() 函数中 return 为 True 的元素的索引?
Is there a way to return the index of an element that returns True in the any() function?
(这只是我想解决的一个例子)
array = ["hello", "hi"]
statement = input()
condition = any(statement in elm for elm in array)
有没有办法 return return 为 True 的元素的索引,或者我应该只使用 for 循环?
实际上你想要 array
中语句的 index
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
下次搜索函数属性。我根据 Python documents
编写示例代码
array = ["hello", "hi", "example", "to get", "index from array"]
def SearchIndex():
statement = input()
#// Check if input is item on list
if statement in array: print(">>", array.index(statement))
#// Other search if input is part of item in list
else:
part_of = False
for item in array:
if statement in item:
print('>> {0} is part of "{2}" -> {1}'.format(statement, array.index(item), array[array.index(item)]))
#// If founded signal
part_of = True
#// If nout found (signal is false)
if part_of == False: print(f">> {statement} is not on list...")
while 1:
SearchIndex()
(这只是我想解决的一个例子)
array = ["hello", "hi"]
statement = input()
condition = any(statement in elm for elm in array)
有没有办法 return return 为 True 的元素的索引,或者我应该只使用 for 循环?
实际上你想要 array
index
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
下次搜索函数属性。我根据 Python documents
编写示例代码array = ["hello", "hi", "example", "to get", "index from array"]
def SearchIndex():
statement = input()
#// Check if input is item on list
if statement in array: print(">>", array.index(statement))
#// Other search if input is part of item in list
else:
part_of = False
for item in array:
if statement in item:
print('>> {0} is part of "{2}" -> {1}'.format(statement, array.index(item), array[array.index(item)]))
#// If founded signal
part_of = True
#// If nout found (signal is false)
if part_of == False: print(f">> {statement} is not on list...")
while 1:
SearchIndex()