寻求Python中通过索引列表获取元素列表的快捷方法(wxPython相关)
有没有列表推导式之外的快捷方法批量获取指定索引的元素?
嘿,这个问题问到点子上了!Python标准的list确实没有内置像getitems()这样直接按索引列表取元素的方法,但咱们有几种简洁又实用的替代方案,完全能满足你从wxPython组件返回的索引列表中提取对应元素的需求:
1. 使用operator.itemgetter(推荐,无额外依赖)
这是标准库operator模块里的工具,专门用来批量获取序列的元素,写法非常紧凑:
from operator import itemgetter list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five'] list_of_indexes = [1,3,5] # 直接获取元素,返回元组,转成列表只需套个list() selected_items = itemgetter(*list_of_indexes)(list_of_items) print(list(selected_items)) # 输出: ['one', 'three', 'five']
这个方法的效率和列表推导式不相上下,而且代码更简洁,特别适合处理wx控件返回的索引列表场景。
2. 借助numpy数组(适合数据密集型场景)
如果你的项目已经在使用numpy,那numpy数组的索引语法完美贴合你想要的getitems风格:
import numpy as np arr_items = np.array(['zero', 'one', 'two', 'three', 'four', 'five']) list_of_indexes = [1,3,5] selected_items = arr_items[list_of_indexes].tolist() print(selected_items) # 输出: ['one', 'three', 'five']
这种写法直观到几乎和你设想的list_of_items.getitems(list_of_indexes)一模一样,唯一需要注意的是要先把普通列表转成numpy数组。
3. 自己封装工具函数(按需定制)
要是你经常需要这种操作,可以自己写个简单的工具函数,用法完全符合你的预期:
def get_items(lst, indexes): return [lst[i] for i in indexes] list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five'] list_of_indexes = [1,3,5] print(get_items(list_of_items, list_of_indexes)) # 输出: ['one', 'three', 'five']
甚至你可以用猴子补丁给list类临时加个方法(小脚本里用着很方便,大型项目不推荐):
list.getitems = lambda self, indexes: [self[i] for i in indexes] print(list_of_items.getitems(list_of_indexes)) # 输出: ['one', 'three', 'five']
以上几种方案都能替代你原来的列表推导式,选哪种就看你的项目依赖和使用场景啦~
内容的提问来源于stack exchange,提问作者DamirX
相关产品推荐
相关产品推荐

