Python 專題五 列表基礎(chǔ)知識(二維list排序、獲取下標(biāo)和處理txt文本實(shí)例)
通常測試人員或公司實(shí)習(xí)人員需要處理一些txt文本內(nèi)容,而此時(shí)使用Python是比較方便的語言。它不光在爬取網(wǎng)上資料上方便,還在NLP自然語言處理方面擁有獨(dú)到的優(yōu)勢。這篇文章主要簡單的介紹使用Python處理txt漢字文字、二維列表排序和獲取list下標(biāo)。希望文章對你有所幫助或提供一些見解~
一. list二維數(shù)組排序
功能:已經(jīng)通過Python從維基百科中獲取了國家的國土面積和排名信息,此時(shí)需要獲取國土面積并進(jìn)行排序判斷世界排名是否正確。
列表基礎(chǔ)知識
列表類型同字符串一樣也是序列式的數(shù)據(jù)類型,可以通過下標(biāo)或切片操作來訪問某一個或某一塊連續(xù)的元素。它和字符串不同之處在于:字符串只能由字符組成而且不可變的(不能單獨(dú)改變它的某個值),而列表是能保留任意數(shù)目的Python對象靈活容器。
總之,列表可以包含不同類型的對象(包括用戶自定義的對象)作為元素,列表可以添加或刪除元素,也可以合并或拆分列表,包括insert、update、remove、sprt、reverse等操作。
列表排序介紹
常用列表排序方法包括使用List內(nèi)建函數(shù)list.sort()或序列類型函數(shù)sorted(list)排序
#list.sort(func=None, key=None, reverse=False) list = [4, 3, 9, 1, 5, 2] print list list.sort() print list #輸出 [4, 3, 9, 1, 5, 2] [1, 2, 3, 4, 5, 9]
通過對比下面的代碼,可以發(fā)現(xiàn)兩種方法的區(qū)別是:list.sort()改變了原list的順序,而sorted沒有。
#sorted(list) list = ['h', 'a', 'p', 'd', 'i', 'b'] print list print sorted(list) print list #輸出 ['h', 'a', 'p', 'd', 'i', 'b'] ['a', 'b', 'd', 'h', 'i', 'p'] ['h', 'a', 'p', 'd', 'i', 'b']
二維列表排序
通過lambda表達(dá)式實(shí)現(xiàn)二維列表排序,并且按照第二個關(guān)鍵字進(jìn)行排序。參考文章
#list.sort(func=None, key=None, reverse=False) list = [('Tom',4),('Jack',7),('Daly',9),('Mary',1),('God',5),('Yuri',3)] print list list.sort(lambda x,y:cmp(x[1],y[1])) print list #輸出 [('Tom', 4), ('Jack', 7), ('Daly', 9), ('Mary', 1), ('God', 5), ('Yuri', 3)] [('Mary', 1), ('Yuri', 3), ('Tom', 4), ('God', 5), ('Jack', 7), ('Daly', 9)]
題目中如果第一個數(shù)存儲文件中讀取的行號,第二個數(shù)存儲人口數(shù)量,此時(shí)可對第二個數(shù)進(jìn)行排序。需要注意的是它們一組(1,93)是tuple元組。
#list.sort(func=None, key=None, reverse=False) list = [(1,93),(2,71),(3,89),(4,93),(5,85),(6,77)] print list list.sort(key=lambda x:x[1]) print list #輸出 [(1, 93), (2, 71), (3, 89), (4, 93), (5, 85), (6, 77)] [(2, 71), (6, 77), (5, 85), (3, 89), (1, 93), (4, 93)]
lambada表達(dá)式
在上述代碼中,如果還不知道lambada是什么鬼東西的話?那我就來幫你回顧了。
python允許使用lambda關(guān)鍵字創(chuàng)造匿名函數(shù),它不需要以標(biāo)準(zhǔn)的方式來聲明,如def語句。然而作為函數(shù),它們也能有參數(shù)。
lambda就是一個表達(dá)式,而不是一個代碼塊。而且這個表達(dá)是的定義必須和聲明放在同一行,能在lambda中封裝有限的邏輯進(jìn)去,起到一個函數(shù)速寫的作用。例如:
#lambda [arg1[, arg2, ..., argN]]:expression f = lambda x,y,z:x+y+z num = f(1,2,3) print 'lambda: ' + str(num) #等價(jià)于 def add(x,y,z): return x+y+z num = add(1,2,3) print 'function: ' + str(num) #輸出 lambda: 6 function: 6
二. 處理txt文本
下面是通過txt文件按行讀取,并獲取面積進(jìn)行排序。其中核心代碼如下:
讀取文件&列表添加
source = open("F:\\Student\\1Area.txt",'r') lines = source.readlines() L = [] #列表二維 國家行數(shù) 人口數(shù) count = 1 #當(dāng)前國家在文件中第count行 for line in lines: line = line.rstrip('\n') #去除換行 .... #獲取排名和面積 fNum = string.atof(number) #面積 L.append((count,ffNum)) #列表添加 count = count + 1 else: print 'End While' source.close()
列表排序
L.sort(lambda x,y:cmp(x[1],y[1]),reverse = True) #遍歷過程 表示第i名 (文件第x行,面積y平方公里) #重點(diǎn) L[i]輸出列表 1 (46, 17075200.0) L[i][0]表示元組tuple第一個數(shù) 1 46 for i in range(len(L)): print (i+1), L[i]
獲取面積字符串
line = line.rstrip('\n') #去除換行 start = line.find(r'V:') end = line.find(r'平方公里') number = line[start+2:end] number = number.replace(',','') #去除',' #輸出 line => C:國家 E:中華人民共和國 A:國土面積 V:9,634,057或9,736,000平方公里(世界第3/4名) number => 9634057或9736000
最后同時(shí)需要處理各種字符串情況,如‘或'、‘萬'要乘10000、刪除‘[1]'等。更簡單的方法是通過正則表達(dá)式或獲取第一個非數(shù)字字符。
運(yùn)行結(jié)果如下所示,排序后的txt和糾錯txt:
代碼如下:
# coding=utf-8 import time import re import os import string import sys source = open("F:\\Student\\1Area.txt",'r') lines = source.readlines() count = 1 L = [] #列表二維 國家行數(shù) 人口數(shù) ''''' 第一部分 獲取國土面積 ''' print 'Start!!!' for line in lines: line = line.rstrip('\n') #去除換行 start = line.find(r'V:') end = line.find(r'平方公里') number = line[start+2:end] number = number.replace(',','') #去除',' fNum = 0.0 if '萬' in number: end = line.find(r'萬') newNum = line[start+2:end] fNum = string.atof(newNum)*10000 else: #如何優(yōu)化代碼 全局變量 if '/' in number: end = line.find(r'/') newNum = line[start+2:end] newNum = newNum.replace(',','') fNum = string.atof(newNum) elif '(' in number: end = line.find(r'(') newNum = line[start+2:end] newNum = newNum.replace(',','') fNum = string.atof(newNum) elif '[' in number: end = line.find(r'[') newNum = line[start+2:end] newNum = newNum.replace(',','') fNum = string.atof(newNum) elif '或' in number: end = line.find(r'或') newNum = line[start+2:end] newNum = newNum.replace(',','') fNum = string.atof(newNum) elif ' ' in number: end = line.find(r' ') newNum = line[start+2:end] newNum = newNum.replace(',','') fNum = string.atof(newNum) else: fNum = string.atof(number) #print line #print number #print fNum L.append((count,fNum)) count = count + 1 else: print 'End While' source.close() ''''' 第二部分 從大到小排序 參看 http://blog.chinaunix.net/uid-20775448-id-4222915.html ''' L.sort(lambda x,y:cmp(x[1],y[1]),reverse = True) #print L #遍歷過程 表示第i名 (文件第x行,面積y平方公里) #重點(diǎn) L[i]輸出列表 1 (46, 17075200.0) L[i][0]表示元組tuple第一個數(shù) 1 46 for i in range(len(L)): print (i+1), L[i] ''''' 第三部分 讀寫文件 ''' source = open("F:\\Student\\1Area.txt",'r') lines = source.readlines() result = open("F:\\Student\\1NewArea.txt",'w') count = 1 for line in lines: line = line.rstrip('\n') #獲取列表L中排名位置pm pm = 0 for i in range(len(L)): if count==L[i][0]: pm = i+1 break #獲取文件中名次 if '世界第' in line: start = line.find(r'世界第') end = line.find(r'名') number = line[start+9:end] if '/' in number: #防止中國第3/4名 end = line.find(r'/') number = line[start+9:end] if '包括海外' in number: number = '41' print number,pm,type(number),type(pm) if string.atoi(number)==pm: line = line + ' 【排名正確】 【世界第' + str(pm) + '名】' result.write(line+'\n') else: line = line + ' 【排名錯誤】 【世界第' + str(pm) + '名】' result.write(line+'\n') else: #文件中沒有排名 line = line + ' 【新加排名】 【世界第' + str(pm) + '名】' result.write(line+'\n') count = count + 1 else: print 'End Sorted' source.close() result.close() ''''' 第四部分 輸出一個排序好的文件 便于觀察 ''' source = open("F:\\Student\\1Area.txt",'r') lines = source.readlines() result = open("F:\\Student\\1NewSortArea.txt",'w') #i表示第i名 L[i][0]表示行數(shù) pm = 0 for i in range(len(L)): pm = L[i][0] count = 1 for line in lines: line = line.rstrip('\n') if count==pm: line = line + ' 【世界第' + str(i+1) + '名】' result.write(line+'\n') break else: count = count + 1 else: print 'End Sorted Second' source.close() result.close()
最后希望文章對你有所幫助,文章主要通過講述一個實(shí)際操作,幫你鞏固學(xué)習(xí)liet列表的二維排序和字符串txt處理。如果文中有錯誤或不足之處,還請海涵~
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
卸載tensorflow-cpu重裝tensorflow-gpu操作
這篇文章主要介紹了卸載tensorflow-cpu重裝tensorflow-gpu操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06淺談Python數(shù)據(jù)處理csv的應(yīng)用小結(jié)
這篇文章主要介紹了Python數(shù)據(jù)處理csv的簡單應(yīng)用,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01Python MySQLdb 執(zhí)行sql語句時(shí)的參數(shù)傳遞方式
這篇文章主要介紹了Python MySQLdb 執(zhí)行sql語句時(shí)的參數(shù)傳遞方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03python之pymysql模塊簡單應(yīng)用示例代碼
這篇文章主要介紹了python之pymysql模塊簡單應(yīng)用示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12Python編程之string相關(guān)操作實(shí)例詳解
這篇文章主要介紹了Python編程之string相關(guān)操作,結(jié)合實(shí)例形式分析了Python字符串相關(guān)函數(shù)與常見操作技巧,需要的朋友可以參考下2017-07-07Python 讀取用戶指令和格式化打印實(shí)現(xiàn)解析
這篇文章主要介紹了Python 讀取用戶指令和格式化打印實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09