简体   繁体   English

分割数组时减少内存使用的最佳做法

[英]Best practice to reduce memory usage when splitting array

I have an array that I want to split up in two halves. 我有一个阵列,我想分成两半。 Because of symmetry I am only interested in keeping the left half of the array. 由于对称性,我只对保持数组的左半部分感兴趣。

I can split the array in half by saying: 我可以通过说:

[a,b] = numpy.split(c,2)

where c is also an array. 其中c也是一个数组。

Is there a way to only return the 'a' array, or alternatively removing the 'b' array from memory immediately after splitting the array? 有没有办法只返回'a'数组,或者在拆分数组后立即从内存中删除'b'数组?

You can copy the first half with 你可以复制上半部分

a = x[len(x)//2:].copy()

this would need to allocate the copy and move the content (thus temporarily needing 1.5 times the memory) 这需要分配副本并移动内容(因此暂时需要1.5倍的内存)

Otherwise you can just say 否则你可以说

a = x[len(x)//2:]

to get a reference to the first half, but the other part will not be removed from memory 获取对前半部分的引用,但另一部分不会从内存中删除

Simply you can use delete function for this aim! 您只需使用删除功能即可实现此目标! this is an example : 这是一个例子:

array=np.array([1,2,3,4])
x=len(array)/2
first_h=np.delete(array,array[x-1:])         #second half

Demo: 演示:

>>>print first_h
>>>[1,2]

I'm not sure, but I think this might be best because it relies on list 's implementation ( docs ) and I'm confident it was done right: 我不确定,但我认为这可能是最好的,因为它依赖于list的实现( docs ),我相信它做得对:

>>> r = range(10)
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del r[5:]
>>> r
[0, 1, 2, 3, 4]

See also del statement for lists . 另请参见列表的del语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM