本文實例講述了Python實現多條件篩選目標數據功能。分享給大家供大家參考,具體如下:
python中提供了一些數據過濾功能,可以使用內建函數,也可以使用循環語句來判斷,或者使用pandas庫,當然在有些情況下使用pandas是為了提高工作效率。舉例如下:
a = [('chic', 'JJ'), ('although', 'IN'), ('menu', 'JJ'), ('items', 'NNS'), ('doesnt', 'JJ'), ('scream', 'NN'), ('french', 'JJ'), ('cuisine', 'NN')]
這里的a為一個list,列表中還有元組。每一個元組由單詞和其詞性組成,我們要篩選詞性為JJ何NN的單詞??梢杂腥N寫法:
第一種,使用內建函數filter:
# -*- coding:utf-8 -*-#!python3a = [('chic', 'JJ'), ('although', 'IN'), ('menu', 'JJ'), ('items', 'NNS'), ('doesnt', 'JJ'), ('scream', 'NN'), ('french', 'JJ'), ('cuisine', 'NN')]def filt_nn(data_text): nn_data = filter(lambda x: x[1] == 'NN'or x[1] == 'JJ', data_text)# print(list(nn_data)) return list(nn_data)print(filt_nn(a))
運行結果:
[('chic', 'JJ'), ('menu', 'JJ'), ('doesnt', 'JJ'), ('scream', 'NN'), ('french', 'JJ'), ('cuisine', 'NN')]
第二種,使用pandas包:
# -*- coding:utf-8 -*-#!python3import pandas as pda = [('chic', 'JJ'), ('although', 'IN'), ('menu', 'JJ'), ('items', 'NNS'), ('doesnt', 'JJ'), ('scream', 'NN'), ('french', 'JJ'), ('cuisine', 'NN')]data = pd.DataFrame(a, columns=['word', 'ps'])print(data[data.ps.isin(['JJ', 'NN'])].word)
運行結果:
0 chic
2 menu
4 doesnt
5 scream
6 french
7 cuisine
Name: word, dtype: object
第三種,使用循環:
# -*- coding:utf-8 -*-#!python3a = [('chic', 'JJ'), ('although', 'IN'), ('menu', 'JJ'), ('items', 'NNS'), ('doesnt', 'JJ'), ('scream', 'NN'), ('french', 'JJ'), ('cuisine', 'NN')]absd = []for i in a: if i[1] == 'NN' or i[1] == 'JJ': absd.append(i[0])print(absd)
得到的結果都相同,如下:
['chic', 'menu', 'doesnt', 'scream', 'french', 'cuisine']
雖然結果相同,但是推薦第一、二種方法,因為這兩個方法速度更快。
更多關于Python相關內容可查看本站專題:《Python列表(list)操作技巧總結》、《Python字符串操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
疑難解答