在列表的不同索引点插入值

时间:2018-08-09 15:31:17

标签: python numpy

假设我有一个开始列表:

<header>header</header>
<main>
  <article>content</article>
  <article>content</article>
  <article>content</article>
  <article>content</article>
  <article>content</article>
  <article>content</article>
  <article>content</article>
</main>
<footer>footer</footer>

我现在选择从以下位置的列表中删除/删除三个项目:

SELECT TableA.id AS tableA_id, -- Or anything you want to name it after 'AS'
       TableB.id AS tableB_id
  FROM TableA
 INNER
  JOIN TableB
    ON TableA.key = TableB.key

使用Numpy可以通过以下方式完成

start_list = [0, 2, 3, 5, 6, 10, 11, 14, 20]

现在,我希望返回remove_list = [0, 3, 5] 的原始结构,但是当然要删除与之不同的值,即类似这样的东西:

>> final_list = np.delete(start_list, remove_list, axis=0)
[2, 3, 6, 11, 14, 20]

因此删除的索引现在已恢复为与开头相同的排列,但是删除的值现在已替换为零。

如果我使用类似start_list的东西,则会得到一个新列表,在new_list = [0, 2, 3, 0, 6, 0, 11, 14, 20] 的索引位置插入零。但是,这是相对于numpy.insert(final_list, remove_list, 0)索引而言的,因此其结尾为:

remove_list

显然与final_list不同。

如果我像这样迭代:

new_list = [0, 2, 3, 6, 0, 11, 14, 0, 20]

最后我得到了三个数组,其中每个索引中的start_list的索引中都插入了一个零。

所以基本上,我只是想从new_final_list = [np.insert(final_list, k, 0) for k in remove_list] “重新创建” remove_list,但是要删除的值的位置为零。

2 个答案:

答案 0 :(得分:3)

enumerate使用列表理解:

new_list = [x if i not in remove_list else 0 for i, x in enumerate(start_list)]
print(new_list)
#[0, 2, 3, 0, 6, 0, 11, 14, 20]

答案 1 :(得分:0)

In [453]: start_list = [0, 2, 3, 5, 6, 10, 11, 14, 20]
In [454]: remove_list = [0, 3, 5]

如果我们从start_list中创建一个数组,则很容易用新值(例如0)替换选定的项。删除并重新插入是困难的方法:

In [455]: arr = np.array(start_list)
In [456]: arr[remove_list] = 0
In [457]: arr
Out[457]: array([ 0,  2,  3,  0,  6,  0, 11, 14, 20])

通过列表理解,从列表中删除项目很容易。这是@pault的替换理解的一种变体:

In [458]: [x for i,x in enumerate(start_list) if i not in remove_list]
Out[458]: [2, 3, 6, 11, 14, 20]

np.delete可以从数组(或将列表变成数组)中删除项目,但是在内部它很复杂(由于其通用性)。我认为在这种情况下,它仅使用布尔掩码:

In [459]: mask = np.ones(len(start_list), bool)
In [460]: mask[remove_list] = False
In [461]: mask
Out[461]: array([False,  True,  True, False,  True, False,  True,  True,  True])
In [462]: arr[mask]
Out[462]: array([ 2,  3,  6, 11, 14, 20])

明智的选择时间,如果您从列表开始,坚持列表会更快。创建数组会产生开销,而诸如此类的操作无法克服。

可以通过切片从列表中删除元素

In [464]: for i in remove_list[::-1]:
     ...:     start_list[i:i+1] = []
     ...:     
In [465]: start_list
Out[465]: [2, 3, 6, 11, 14, 20]

但是我们必须从remove_list的末尾开始,以避免弄乱计数。这是一个相对知名的Python列表习惯用法。

我们可以以相同的方式将元素插入列表,但是我们必须调整索引以适应中间大小。

In [483]: insert_list = [i-j for i,j in zip(remove_list,range(3))]
In [484]: start_list=[2,3,6,11,14,20]
In [485]: for i in insert_list[::-1]:
     ...:     start_list[i:i] = [0]
     ...:     
     ...:     
In [486]: start_list
Out[486]: [0, 2, 3, 0, 6, 0, 11, 14, 20]

我通过反复试验得出了insert_list,并从期望的结果中进行了尝试。

相关问题