You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:15:38