我有蟒蛇列表,我想要得到的一组索引出来的,并保存为原始列表的一个子集:通过索引列表的Python选择元件
templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]
,我想这:
sublist=[[1, 4, 7, 16, 19,20]]
作为一个例子。
我无法预先知道列表元素的内容是什么。我所拥有的是指标总是一样的。
有没有一种方法可以做到这一点?
我有蟒蛇列表,我想要得到的一组索引出来的,并保存为原始列表的一个子集:通过索引列表的Python选择元件
templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]
,我想这:
sublist=[[1, 4, 7, 16, 19,20]]
作为一个例子。
我无法预先知道列表元素的内容是什么。我所拥有的是指标总是一样的。
有没有一种方法可以做到这一点?
假设您知道要选择什么样的指数,它的工作是这样的:
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[i])
这也可以在列表理解的形式来表达 -
sublist = [templist[0][i] for i in indices]
您可以使用列表中理解并具有枚举:
indices = [1,2,3]
sublist = [element for i, element in enumerate(templist) if i in indices]
>>> 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]]
您可以使用列表理解:
indices = set([1,2,3])
sublist = [el for i, el in enumerate(orig_list) if i in indices]
或者你可以存储索引列表中True/False并使用itertools.compress
:
indices = [True, False, True]
sublist = itertools.compress(orig_list, indices)
指数如何储存? –
你是什么意思? Python给列表中的每个元素都有自己的索引? – testname123
所以告诉我,如果我正确地理解了这一点:你有一个列表,你有一些索引,并且你想提取一个包含这些索引列表元素的子列表。 –