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\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 '' 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\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 in cpuDetail2:
 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迭代的值為 ‘’ ‘’ ‘’然后越界,所以,只能刪除前五個空元素。

這個問題算是大家非常容易忽略的細節問題。在遍歷列表時,特別要注意遍歷過程中不要對原列表進行增刪操作,以免影響迭代過程

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM