删除数组零元素
- 问题描述
- 样例输入
- 样例输入2
- 样例输入3
- 样例输出
- 样例输出2
- 样例输出3
- 解题思路
- 代码实现
问题描述
从键盘读入n个整数放入数组中,编写函数CompactIntegers,删除数组中所有值为0的元素,其后元素向数组首端移动。注意,CompactIntegers函数需要接受数组及其元素个数作为参数,函数返回值应为删除操作执行后数组的新元素个数。输出删除后数组中元素的个数并依次输出数组元素。
样例输入
(输入格式说明:5为输入数据的个数,3 4 0 0 2 是以空格隔开的5个整数)
5
3 4 0 0 2
样例输入2
7
0 0 7 0 0 9 0
样例输入3
3
0 0 0
样例输出
(输出格式说明:3为非零数据的个数,3 4 2 是以空格隔开的3个非零整数)
3
3 4 2
样例输出2
2
7 9
样例输出3
0
解题思路
这道题的主题是“删除数组零元素”,不妨我们换个思路,把符合要求的元素拿出来,组成新的列表。
根据这一思路,写出代码。
代码实现
def CompactIntegers(n, arr):
newArr = []
for item in range(n):
if arr[item] != 0:
newArr.append(arr[item])
print(len(newArr))
for item in newArr:
print(item, end=" ")
return len(newArr)
def main():
n = int(input())
arr = list(map(int,input().split()))
CompactIntegers(n, arr)
main()