我有一个数组a
,如果数组中的元素为偶数或正数,则希望将a
的元素重复n次。我的意思是只希望重复满足某些条件的元素。
例如,如果a=[1,2,3,4,5]
,n=2
,条件是偶数,则我想要a
变成a=[1,2,2,3,4,4,5]
。
np.clip
和np.repeat
。n = 2
a = np.asarray([1,2,3,4,5])
cond = (a % 2) == 0 #condition is True on even numbers
m = np.repeat(a, np.clip(cond * n, a_min=1, a_max=None))
In [124]: m
Out[124]: array([1, 2, 2, 3, 4, 4, 5])
或者您可以使用numpy的ndarray.clip
而不是np.clip
,这样命令会更短。
m = np.repeat(a, (cond * n).clip(min=1))
itertools
,a = [1,2,3,4,5]
n = 2
# this can be any condition. E.g., even only
cond = lambda x: x % 2 == 0
b = list(itertools.chain.from_iterable( \
(itertools.repeat(x, n) if cond(x) else itertools.repeat(x,1)) \
for x in a))
b
# [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
repeat(x,1)
是为了允许使用chain
并避免需要展平混合整数和生成器的数组...)>>> a = [1,2,3,4,5]
>>> new_a = []
>>> n = 2
>>>
>>> for num in a:
... new_a.append(num)
... if num % 2 == 0:
... for i in range(n-1):
... new_a.append(num)
...
>>> new_a
[1, 2, 2, 3, 4, 4, 5]
import numpy as np
a = np.asarray([1,2,3,4,5])
n = int(input("Enter value of n "))
new_array = []
for i in range(0,len(a)):
counter = np.count_nonzero(a == a[i])
if a[i]%2 != 0:
new_array.append(a[i])
elif a[i]>0 and a[i]%2 == 0:
for j in np.arange(1,n+1):
new_array.append(a[i])