Python实现多条件筛选目标数据功能【测试可用】 本文实例讲述了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的单词。可以有三种写法: 第一种,使用内建函数filter: # -*- coding:utf-8 -*- #!python3 a = [('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 -*- #!python3 import pandas as pd a = [('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 -*- #!python3 a = [('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程序设计有所帮助。