我有蟒蛇列表,我想要得到的一組索引出來的,並保存爲原始列表的一個子集:通過索引列表的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
所以告訴我,如果我正確地理解了這一點:你有一個列表,你有一些索引,並且你想提取一個包含這些索引列表元素的子列表。 –