如何复制列表/数组中的特定值？

问题描述投票：7回答：9

``````array_a = [1, 2, 1, 2, 1, 1, 2]
``````

``````array_a = [1, 2, 2, 1, 2, 2, 1, 1, 2, 2]  # only the `2` should be repeated
``````

python arrays list numpy numpy-ndarray
9个回答
4

``````>>> import numpy as np
>>> np.repeat(array_a, array_a)
array([1, 2, 2, 1, 2, 2, 1, 1, 2, 2])
``````

``````>>> n_repeats = 2
>>> temp = np.where(np.array(array_a) == 2, n_repeats, 1)
>>> np.repeat(array_a, temp)
array([1, 2, 2, 1, 2, 2, 1, 1, 2, 2])
``````

3

``````array_a = [1,2,1,2,1,1,2]

repeat_times = {1:1, 2:2} # 1 is 1 time and 2 is repeated two times

result = [i for i in array_a for j in range(repeat_times[i])]
print(result)
``````

``````[1, 2, 2, 1, 2, 2, 1, 1, 2, 2]
``````

1

``````>>> def repeater(iterable, repeat_map):
...     for value in iterable:
...         for i in range(repeat_map.get(value, 1)):
...             yield value
...
>>> array_a = [1,2,1,2,1,1,2]
>>> list(repeater(array_a, repeat_map={2: 2}))
[1, 2, 2, 1, 2, 2, 1, 1, 2, 2]
``````

1

``````a = [1,2,1,2,1,1,2]
long_a = []
for x in a:
long_a.append(x)
if x == 2:
long_a.append(x)
``````

0

1. 遍历数组（python中的'list'）
2. 找到号码
3. 获取数组中匹配数字的位置
4. 在每个匹配位置后插入另一个数字

https://docs.python.org/3/reference/compound_stmts.html#for

https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

0

``````array = [1, 2, 1, 2, 1, 1, 2]

element_to_repeat = 2

result = [
repeats_element
for repeats in
((element,)*2 if element == element_to_repeat else (element,) for element in array)
for repeats_element in repeats
]
``````

0

``````array = [1, 2, 1, 2, 1, 1, 2]

element_to_repeat = 2

for element in array:
if element == element_to_repeat:
yield element
yield element
else:
yield element

``````

0

``````from itertools import chain
array_a = [1, 2, 1, 2, 1, 1, 2]

list(chain.from_iterable([[item, item] if item == 2 else [item] for item in array_a]))
[1, 2, 2, 1, 2, 2, 1, 1, 2, 2]  # output
``````

double的具体值在if语句中。使用乘数（而不是`[item, item]`）和变量（而不是`2`）会使这更容易更通用，例如：

``````from itertools import chain

def repeat_certain_value(array, val, n):
return list(chain.from_iterable(([i] * n if i == val else [i] for i in array)))

repeat_certain_value([1, 2, 1, 2, 1, 1, 2], 2, 2)
[1, 2, 2, 1, 2, 2, 1, 1, 2, 2]  # output

repeat_certain_value([0, -3, 1], -3, 5)
[0, -3, -3, -3, -3, -3, 1]  # output
``````

``````%timeit for x in range(1000): repeat_certain_value([1, 1, 1, 2, 2, 2, 3, 3, 3] * 100, 2, 2)
10 loops, best of 3: 165 ms per loop

%timeit for x in range(1000): coldspeeds_solution([1, 1, 1, 2, 2, 2, 3, 3, 3] * 100, 2, 2)
10 loops, best of 3: 100 ms per loop
``````

0

``````array_a = [1, 2, 1, 2, 1, 1, 2]
def flat(l):
newl=[]
for i in l:
if isinstance(i,list):
newl.extend(i)
else:
newl.append(i)
return newl
print(flat([[i]*2 if i==2 else i for i in array_a]))
``````

``````[1, 2, 2, 1, 2, 2, 1, 1, 2, 2]
``````