Python列表数据过滤的不同方法汇总
""" 皮蛋编程(https://www.pidancode.com) 创建日期:2022/4/27 功能描述:Python列表数据过滤的不同方法汇总 """ mylist = [1, 4, -5, 10, -7, 2, 3, -1] # 所有正值 pos = [n for n in mylist if n > 0] print(pos) # 所有负值 neg = [n for n in mylist if n < 0] print(neg) # 将负值设置为0 neg_clip = [n if n > 0 else 0 for n in mylist] print(neg_clip) # 将正值设置为0 pos_clip = [n if n < 0 else 0 for n in mylist] print(pos_clip) # 压缩演示 addresses = [ '5412 N CLARK', '5148 N CLARK', '5800 E 58TH', '2122 N CLARK', '5645 N RAVENSWOOD', '1060 W ADDISON', '4801 N BROADWAY', '1039 W GRANVILLE', ] counts = [ 0, 3, 10, 4, 1, 7, 6, 1] from itertools import compress more5 = [ n > 5 for n in counts ] a = list(compress(addresses, more5)) print(a)
输出:
[1, 4, 10, 2, 3] [-5, -7, -1] [1, 4, 0, 10, 0, 2, 3, 0] [0, 0, -5, 0, -7, 0, 0, -1] ['5800 E 58TH', '1060 W ADDISON', '4801 N BROADWAY']
相关文章