从python中的列表中删除对象而不更改索引

时间:2017-04-21 12:42:58

标签: python numpy

我有一个可以简化为这样的列表:

x=[6,5,4,3,0,0,0,2,1]

我希望能够删除零但保留索引,以便在绘制x时,值不会向左偏移。

我使用了numpy.delete这样的函数:

def zeros(array):
b = []
for j in range(len(array)):
    if array[j] == 0:
        b.append(j)
    j += 1
c = np.delete(array, [b])
return c

这是我获得的情节: See how the red curve offsets to the left after all the zeros?

我怎么能解决这个问题?

5 个答案:

答案 0 :(得分:0)

是的,您可以从列表中删除所有零。使用列表理解。

>>> x=[6,5,4,3,0,0,0,2,1]
>>> x = [y for y in x if y != 0]
>>> print x
[6,5,4,3,2,1]

它应该有用。

答案 1 :(得分:0)

尝试:

import numpy as np
import matplotlib.pyplot as plt

x=np.array([1,2,3,4,0,0,0,5,6]).astype(float)
index=np.linspace(0,x.size-1,x.size)
x[x==0]=np.nan #find where x==0 and replace with NaN, which wont show up on graph
plt.plot(index,x,'*')

答案 2 :(得分:0)

考虑使用Pandas:

In [69]: a = pd.Series(x)

In [70]: a
Out[70]:
0    6
1    5
2    4
3    3
4    0
5    0
6    0
7    2
8    1
dtype: int64

In [71]: a.loc[a!=0]
Out[71]:
0    6
1    5
2    4
3    3
7    2
8    1
dtype: int64

plotting

a.loc[a!=0].plot()

答案 3 :(得分:0)

A
B
E
F
15
A

如果元素在列表中是唯一的:

x = [1,2,3,4,0,0,0,5,6]   
x_without_zero = [a for a in x if a!=0]
print x_without_zero
[1, 2, 3, 4, 5, 6]

否则:

indexes_for_x_without_zero_in_x = [x.index(b) for b in x_without_zero]
print indexes_for_x_without_zero_in_x
[0, 1, 2, 3, 7, 8]

答案 4 :(得分:0)

您可以形成一个索引列表,例如:

<ul id="test">
    <li>Sem lacinia quam venenatis vestibulum.</li>
    <li>Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</li>
    <li>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.</li>
</ul>

<button id="button">Sort by Title</button>


(function($) {
    $(function() {
        $("button").click(function() {
            $("li", "#test").sort(function(a, b) {
                return $(a).text() > $(b).text();
            }).appendTo("#test");
            $("button").text("Sort by Default");
        });
    });
})(jQuery);

这会使用from operator import itemgetter t, xprime = zip(*filter(itemgetter(1), enumerate(x))) t # (0, 1, 2, 3, 7, 8) xprime # (6, 5, 4, 3, 2, 1) 获取索引,然后根据原始列表使用enumerate