我试图使用由索引列表组成的变量flist
来检索features
列表中的元素。
flist = [1, 3, 7]
features = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
所需输出:
['b', 'd', 'h']
是否有直接用flist
从features
中提取元素的方法?例如,当我尝试features[flist[i] for i in range(0,len(flist))]
时,我得到一个"无效语法"错误。
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
idxs = [1, 3, 7]
print ([l[i] for i in idxs])
输出:
['b', 'd', 'h']
使用一个简单的列表推导,生成l
中存在于idxs
中包含的索引的元素列表。