zoukankan      html  css  js  c++  java
  • Python 如何删除列表中的空值

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

    1 # -*- coding:utf-8 -*-
    2 
    3 import os
    4 import time
    5 
    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
    
    ']
    

      

    其中输出的列表中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 '' in cpuDetail:
     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
    
    ']
    ['22542', 'u0_a118', '10', '-10', '1.2G', '89M', '70M', 'S', '125', '10.1', '9:53.49', 'com.google.dialer
    
    ']
    

      

    有人会提出疑问,可不可以用 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 ("删除空值前的输出如下:
    ",cpuDetail1)
     5 cpuDetail2 = cpuInfo.split(" ")
     6 
     7 for i in cpuDetail2:
     8     if i == '':
     9         cpuDetail2.remove(i)
    10 print ("删除空值后的输出如下:
    ",cpuDetail2)

    输出如下:

    删除空值前的输出如下:
     ['22542', 'u0_a118', '', '', '', '', '', '10', '-10', '1.2G', '', '94M', '', '70M', 'R', '', '130', '', '10.7', '', '10:10.79', 'com.google.dialer
    
    ']
    删除空值后的输出如下:
     ['22542', 'u0_a118', '10', '-10', '1.2G', '94M', '70M', 'R', '130', '', '10.7', '', '10:10.79', 'com.google.dialer
    
    ']
    

      

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

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

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

  • 相关阅读:
    数据库备份,全备份、增量备份与恢复
    虚拟机扩容---续集(热扩容)
    虚拟机扩容
    Linux下R环境安装
    OLAP、OLTP的介绍CBO/RBO
    CRC校验(转)
    产品经理必读的30本书单(转)
    xcode6 下 ios simulator 有 Home 键么?
    如果我可以重新学习iOS开发(转)
    按位与、或、异或等运算方法(转)
  • 原文地址:https://www.cnblogs.com/aziji/p/9957507.html
Copyright © 2011-2022 走看看