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
相关产品推荐
相关产品推荐

