开发者

Python: how do I replace all of the same elements in an int array?

I have 1,2,3,6,7,8,1,1,1,6,7,5

What is the syntax 开发者_高级运维for replacing all 1's with ... say.. 0?

for strings its .replace("1", "0")


If by "array" you mean "list":

[0 if e == 1 else e for e in a]

where a is your list.

If by "array" you mean array.array:

array.array('i', [0 if e == 1 else e for e in a])


I just wanted to mention can also use numpy arrays, in which case you can do the following:

import numpy
a = numpy.array([1,2,3,6,7,8,1,1,1,6,7,5])
numpy.where(a==1,0,a)


For large lists whith only a few occurrences of 1, the following is more efficient for changing the list in place than the naive for-loop:

i = a.index(1)
try:
    while True:
        a[i] = 0
        i = a.index(1, i + 1)
except ValueError:
    pass

This is also less readable than the naive for-loop, so only use it if performance matters.


If your "array" is a "list" you can do a list comprehension:

x = [1,2,3,6,7,8,1,1,1,6,7,5]
x = [item if item != 1 else 0 for item in x]

This of course creates a new list. If your list is really big and you don't want to create a new one you could do this instead:

for i, item in enumerate(x):
    if item == 1:
        x[i] = 0

Or this:

for i in xrange(len(x)):
    if x[i] == 1:
        x[i] == 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜