python删除列表空元素_Python 如何删除列表中的空值

今天在获取android性能CPU测试数据时,发现这么一个问题:

1 #-*- coding:utf-8 -*-

2

3 importos4 importtime5

6 cpuInfo = os.popen(r'adb shell top -d 1 -n 1 | findstr com.google.dialer').read()7 print(cpuInfo)8 cpuDetail = cpuInfo.split(" ")9 print (cpuDetail)

输出为:

22542 u0_a118 10 -10 1.2G 143M 81M S 148 16.2 9:29.80 com.google.dialer

['22542', 'u0_a118', '', '', '', '', '', '10', '-10', '1.2G', '143M', '', '81M', 'S', '', '148', '', '16.2', '', '', '9:29.80', 'com.google.dialer\n\n']

其中输出的列表中148这个值本为我要获取的CPU数据,本以为这个列表相对固定,我就直接去通过列表索引[15]即可获得该值,但发现多执行几次之后,所要的CPU数据并不是在固定位置,有时在第15位,有时在第16位,本能的觉得这个通过相对位置不可靠,得找一个可靠的方法才行。

仔细瞧这些列表,发现在CPU数值前面的全部是空值,其它项是每次都会有值输出,那么就好办了只要使用列表的 remove方法将空值删除不就可以了。

下面是删除空值方法:

1 cpuInfo = os.popen(r'adb shell top -d 1 -n 1 | findstr com.google.dialer').read()2 print(cpuInfo)3 cpuDetail = cpuInfo.split(" ")4 #方法一

5 while '' incpuDetail:6 cpuDetail.remove('')7 print(cpuDetail)8

9 #方法二

10 new_list = [i for i in cpuDetail if i !='']11 print (new_list)

两种删除列表空值方法的输出如下:

['22542', 'u0_a118', '10', '-10', '1.2G', '89M', '70M', 'S', '125', '10.1', '9:53.49', 'com.google.dialer\n\n']

['22542', 'u0_a118', '10', '-10', '1.2G', '89M', '70M', 'S', '125', '10.1', '9:53.49', 'com.google.dialer\n\n']

有人会提出疑问,可不可以用 for 循环来操作,接下来会告诉你为什么不能用for 循环,如下:

1 cpuInfo = os.popen(r'adb shell top -d 1 -n 1 | findstr com.google.dialer').read()2 print(cpuInfo)3 cpuDetail1 = cpuInfo.split(" ")4 print ("删除空值前的输出如下:\n",cpuDetail1)5 cpuDetail2 = cpuInfo.split(" ")6

7 for i incpuDetail2:8 if i == '':9 cpuDetail2.remove(i)10 print ("删除空值后的输出如下:\n",cpuDetail2)

输出如下:

删除空值前的输出如下:

['22542', 'u0_a118', '', '', '', '', '', '10', '-10', '1.2G', '', '94M', '', '70M', 'R', '', '130', '', '10.7', '', '10:10.79', 'com.google.dialer\n\n']

删除空值后的输出如下:

['22542', 'u0_a118', '10', '-10', '1.2G', '94M', '70M', 'R', '130', '', '10.7', '', '10:10.79', 'com.google.dialer\n\n']

通过输出可以看出它只把前面五个空值给删除了,后面的空值还是仍然存在。

for的计数器是依次递增的,但列表的内容已通过remove更改,i迭代的值为 ‘’ ‘’ ‘’然后越界,所以,只能删除前五个空元素。

这个问题算是大家非常容易忽略的细节问题。在遍历列表时,特别要注意遍历过程中不要对原列表进行增删操作,以免影响迭代过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值