如何在Python元组中查找指定元素并输出其索引?
查找元组元素的索引方法
你可以利用Python元组内置的index()方法来获取元素的索引,直接在现有代码基础上修改即可:
a = (1,2,3,4) b = int(input('enter the element you want to find')) if b in a : print(f"found at index: {a.index(b)}")
补充说明
a.index(b)会返回元素b在元组a中第一次出现的索引位置。- 如果元组里存在多个相同元素(比如
a = (1,2,3,2,4)),index()只会返回第一个匹配项的索引。如果需要获取所有匹配元素的索引,可以用遍历的方式实现:
a = (1,2,3,2,4) b = int(input('enter the element you want to find')) indices = [i for i, elem in enumerate(a) if elem == b] if indices: print(f"found at indices: {indices}") else: print("element not found")
内容的提问来源于stack exchange,提问作者ganesh murthy
相关产品推荐
相关产品推荐

