使用包含索引列表的变量检索列表元素



我试图使用由索引列表组成的变量flist来检索features列表中的元素。

flist = [1, 3, 7]
features = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

所需输出:

['b', 'd', 'h']

是否有直接用flistfeatures中提取元素的方法?例如,当我尝试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中包含的索引的元素列表。

最新更新