tes*_*123 2 python indexing list set
我在 python 中有一个列表,我想从中获取一组索引并将其保存为原始列表的子集:
templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]
Run Code Online (Sandbox Code Playgroud)
我想要这个:
sublist=[[1, 4, 7, 16, 19,20]]
Run Code Online (Sandbox Code Playgroud)
举个例子。
我无法提前知道列表元素的内容是什么。我所拥有的只是始终相同的索引。
有没有单行方式来做到这一点?
>>> templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]
>>> import operator
>>> f = operator.itemgetter(0,3,6,15,18,19)
>>> sublist = [list(f(templist[0]))]
>>> sublist
[[1, 4, 7, 16, 19, 20]]
Run Code Online (Sandbox Code Playgroud)
假设您知道要选择的索引是什么,它的工作原理如下:
indices = [1, 4, 7, 16, 19, 20]
templist = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]]
sublist = []
for i in indices:
sublist.append(templist[0][i])
Run Code Online (Sandbox Code Playgroud)
这也可以用列表理解的形式来表达 -
sublist = [templist[0][i] for i in indices]
Run Code Online (Sandbox Code Playgroud)