博客
关于我
数组去去零,同一列表操作数值删除添加
阅读量:307 次
发布时间:2019-03-03

本文共 673 字,大约阅读时间需要 2 分钟。

要将数组中的所有零移动到末尾,同时保持非零元素的相对顺序,可以采用以下方法:

方法一:从后往前遍历

这个方法的核心思想是从数组的末尾开始遍历,遇到零时将其移动到末尾。这种方法避免了因删除元素导致索引变化的问题,从而保证了非零元素的相对顺序。

代码实现

nums = [0, 1, 0, 3, 12]for i in range(len(nums)-1, -1, -1):    if nums[i] == 0:        nums.append(nums[i])        nums.pop(i)print(nums)  # 输出: [1, 3, 12, 0, 0]

方法二:使用变量记录零的位置

另一种方法是使用一个变量来记录零的位置。当遇到非零元素时,将其移到记录位置后面,然后将零移动到末尾。

代码实现

nums = [0, 1, 0, 3, 12]j = 0for i in range(len(nums)):    if nums[i] == 0:        nums.append(nums[i])        nums.pop(i)    else:        j += 1print(nums)  # 输出: [1, 3, 12, 0, 0]

示例验证

输入:[0, 1, 0, 3, 12]

  • 方法一:经过两次移动,零移动到末尾,输出为 [1, 3, 12, 0, 0]
  • 方法二:同样经过两次移动,零移动到末尾,输出为 [1, 3, 12, 0, 0]

这两种方法都能高效地解决问题,且在操作次数上表现优异。

转载地址:http://woml.baihongyu.com/

你可能感兴趣的文章
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>