以下是一个示例代码,演示如何根据值或文本查找选择索引:
def find_index(choices, query):
for i, choice in enumerate(choices):
if query in choice or query == choice:
return i
return -1
choices = ['apple', 'banana', 'orange', 'pear', 'grape']
query = 'orange'
index = find_index(choices, query)
if index != -1:
print(f'Found at index: {index}')
else:
print('Not found')
在这个示例中,find_index
函数接收一个选择列表和一个查询值或文本作为参数。它使用enumerate
函数遍历选择列表,并检查每个选择是否包含查询值或与查询值相等。如果找到匹配项,它返回相应的索引值。如果未找到匹配项,它返回-1。
在示例中,我们使用choices
列表和query
值来调用find_index
函数。如果找到匹配项,将打印出相应的索引值。否则,将打印出"Not found"。在这种情况下,'orange'
在choices
列表中的索引为2,所以输出将是"Found at index: 2"。
上一篇:按值或名称切换C#标志枚举
下一篇:按值将对象降序排序。