使用Python,给定数组[1,2,3,4,5],如何得到在这个数组的每个元素之间插入3个0后的新数组
时间: 2023-05-18 22:06:18 浏览: 114
可以使用列表推导式来实现:
```python
arr = [1, 2, 3, 4, 5]
new_arr = [x for x in arr for _ in range(3)] + [0] * 12
```
这里使用了两个列表推导式,第一个用来在原数组的每个元素之间插入3个0,第二个用来在新数组的末尾添加12个0,使得新数组的长度与原数组的长度相同。
相关问题
用python 给定数组[1, 2, 3, 4, 5],在这个数组的每个元素之间插入3个0生成新数组
可以使用以下代码实现:
```python
arr = [1, 2, 3, 4, 5]
new_arr = []
for i in range(len(arr)):
new_arr.append(arr[i])
for j in range(3):
new_arr.append(0)
```
生成的新数组为:[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0]
python代码给定数组[1,2,3,4,5],如何得到在这个数组的每个元素之间插入3个0后的新数组
可以使用以下代码实现:
```python
arr = [1, 2, 3, 4, 5]
new_arr = []
for i in range(len(arr)):
new_arr.append(arr[i])
for j in range(3):
new_arr.append(0)
new_arr.pop() # 去掉最后一个多余的0
print(new_arr)
```
输出结果为:`[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5]`
阅读全文
相关推荐
















