欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python实现多条件筛选目标数据功能【测试可用】

时间:2021-05-10 08:43:43|栏目: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程序设计有所帮助。

上一篇:Collatz 序列、逗号代码、字符图网格实例

栏    目:Python代码

下一篇:Python编程中装饰器的使用示例解析

本文标题:Python实现多条件筛选目标数据功能【测试可用】

本文地址:http://www.codeinn.net/misctech/118355.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有