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

Python列表索引报错:如何按索引获取非连续元素?

获取Python列表的非连续索引元素

Python普通列表不支持直接用x[0,2]这种元组索引获取非连续元素,以下是几种简单实现方式:

  • 列表推导式:遍历目标索引逐个取出元素

    x = [(1,2),(3,4),(5,6)]
    indices = [0, 2]
    result = [x[i] for i in indices]
    print(result)  # 输出: [(1, 2), (5, 6)]
    
  • 使用operator.itemgetter:批量获取元素的高效方式

    from operator import itemgetter
    
    x = [(1,2),(3,4),(5,6)]
    get_items = itemgetter(0, 2)
    result = get_items(x)
    print(result)  # 输出: ((1, 2), (5, 6))
    # 如需列表形式,可转换:list(get_items(x))
    
  • 手动索引拼接:索引数量少时直接组合元素

    x = [(1,2),(3,4),(5,6)]
    result = [x[0], x[2]]
    print(result)  # 输出: [(1, 2), (5, 6)]
    

注意:切片x[0:2]是获取索引0到1(左闭右开)的连续元素,和非连续索引获取逻辑完全不同。

内容的提问来源于stack exchange,提问作者someguyinafloppyhat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:54:51