簡體   English   中英

在python中使用索引創建一個包含列表子集的新列表

[英]creating a new list with subset of list using index in python

一個列表:

a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]

我想要一個使用a[0:2],a[4], a[6:]的子集的列表,

那就是我想要一個列表['a', 'b', 4, 6, 7, 8]

假設

a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]

並且索引列表存儲在

b= [0, 1, 2, 4, 6, 7, 8]

那么一個簡單的單線解決方案就是

c = [a[i] for i in b]

嘗試new_list = a[0:2] + [a[4]] + a[6:]

或者更一般地說,這樣的事情:

from itertools import chain
new_list = list(chain(a[0:2], [a[4]], a[6:]))

這也適用於其他序列,並且可能更快。

或者你可以這樣做:

def chain_elements_or_slices(*elements_or_slices):
    new_list = []
    for i in elements_or_slices:
        if isinstance(i, list):
            new_list.extend(i)
        else:
            new_list.append(i)
    return new_list

new_list = chain_elements_or_slices(a[0:2], a[4], a[6:])

但請注意,如果列表中的某些元素本身就是列表,則會導致問題。 要解決這個問題,要么使用以前的解決方案之一,要么將a[4]替換a[4:5] (或更常見的a[n]a[n:n+1] )。

以下定義可能比提出的第一個解決方案更有效

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

然后你可以像下面一樣使用它

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

該線程已有多年歷史,我不知道當時是否存在該方法,但是到目前為止,答案中沒有提到我在 2022 年找到的最快解決方案。 我的示例列表包含從 1 到 6 的整數,我想從該列表中檢索 4 個項目。

我在安裝了 Python 3.7.4 的 Windows 10 系統上使用了 Jupyter Notebook / iPython 的 %timeit 功能。

我添加了一個 numpy 方法只是為了看看它有多快。 原始問題中的混合類型集合可能需要更多時間。

最快的解決方案似乎是來自操作員模塊(標准庫)的 itemgetter。 如果返回是元組還是列表無關緊要,請按原樣使用 itemgetter 或以其他方式使用列表轉換。 這兩種情況都比其他解決方案更快。

from itertools import chain
import numpy as np
from operator import itemgetter
# 
my_list = [1,2,3,4,5,6]
item_indices = [2, 0, 1, 5]
# 
%timeit itemgetter(*item_indices)(my_list)
%timeit list(itemgetter(*item_indices)(my_list))
%timeit [my_list[item] for item in item_indices]
%timeit list(np.array(my_list)[item_indices])
%timeit list(chain(my_list[2:3], my_list[0:1], my_list[1:2], my_list[5:6]))

輸出是:

184 ns ± 14.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
251 ns ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
283 ns ± 85.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
4.3 µs ± 260 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
663 ns ± 49.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

根據列表的大小和我們要提取的項目數量,我會對哪種解決方案最快的可能偏差感興趣,但這是我當前項目的典型用例。 如果有人有時間對此進行進一步調查,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM