【问题标题】:Is there a way to return the index of an element that returns True in the any() function?有没有办法返回在 any() 函数中返回 True 的元素的索引?
【发布时间】:2020-07-11 08:33:27
【问题描述】:

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

array = ["hello", "hi"]

statement = input()

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

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

【问题讨论】:

  • 什么是elm,一个集合,一个列表?
  • 什么是查询?语句没有使用?
  • “返回true的元素”是什么意思?你打算这个索引做什么?

标签: python python-3.x list any


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    下次搜索函数属性。我基于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()
    

    【讨论】:

    • 我知道如何使用 for 循环获取索引,我问是否有办法在不使用 for 循环的情况下获取索引,谢谢!
    • @LittleNooblet array.index(statement) 不是循环。我在 if 语句之后调用它以避免错误。 else: 之后的内容只是一个示例,说明如何在仅定义一个单词的情况下获取索引。 array.index(statement) 将返回 int() 如果将是 statemenarray item 之间的完美匹配
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 2021-11-09
    相关资源
    最近更新 更多