wxPython中的一些小部件有一个类似"GetSelections()“的方法,它返回所选项目的索引列表。有了这个索引列表,我就可以得到一个项目列表。这样,例如:
>>> list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five']
>>> list_of_indexes = [1,3,5]
>>> [list_of_items[e] for e in list_of_indexes]
['one', 'three', 'five']
所以问题是:最后一个字符串有没有捷径?类似于:
list_of_items.getitems(list_of_indexes)
谢谢!
发布于 2018-05-31 18:41:34
你可以使用的方法很少。
列表切片
用等效的slice
对象替换[1, 3, 5]
:
list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five']
list_of_indexes = slice(1, 6, 2)
res = list_of_items[list_of_indexes]
Itemgetter
如果需要提供slice
无法表示的列表,可以使用operator.itemgetter
from operator import itemgetter
list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five']
list_of_indexes = [1, 3, 5]
res = itemgetter(*list_of_indexes)(list_of_items)
print(res)
('one', 'three', 'five')
Numpy
第三方库numpy
直接支持您所需的索引语法:
import numpy as np
list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five']
list_of_indexes = [1,3,5]
res = np.array(list_of_items)[list_of_indexes].tolist()
https://stackoverflow.com/questions/50621438
复制相似问题