当前位置: 移动技术网 > IT编程>脚本编程>Python > 过滤、修改和替换列表数据

过滤、修改和替换列表数据

2018年07月22日  | 移动技术网IT编程  | 我要评论

暗夜蔷薇魅下载,中国站长之家,vray

##  列表数据的过滤、修改、和替换

 1 # 使用推导式过滤、修改和替换数据
 2 nums = [10,4,33,-54,54,-6,34,-5,23,56,-87,43,-4,3]
 3 new_nums = [i for i in nums if i >= 0] # 过滤掉小于0的元素
 4 print(new_nums)
 5 # [10, 4, 33, 54, 34, 23, 56, 43, 3]
 6 
 7 new_nums = [abs(i) for i in nums]  # 将所有元素值修改为其绝对值
 8 print(new_nums)
 9 # [10, 4, 33, 54, 54, 6, 34, 5, 23, 56, 87, 43, 4, 3]
10 
11 new_nums = [i if i >= 0 else 0 for i in nums] # 将小于0的元素替换为0
12 print(new_nums)
13 # [10, 4, 33, 0, 54, 0, 34, 0, 23, 56, 0, 43, 0, 3]
14 
15 # 使用生成器表达式操作列表以节省内存
16 new_nums = (i for i in nums if i >= 0)
17 print(new_nums)
18 # <generator object <genexpr> at 0x7f4bebb01048>
19 
20 # 对于过滤条件比较复杂的列表,使用filter()函数进行过滤
21 
22 def is_int(item):
23     try:
24         int(item)
25         return True
26     except ValueError:
27         return False
28 
29 items = ['a', '1', '-28', '2.42', 'b', '-8.34']
30 print(list(filter(is_int, items)))
31 # ['1', '-28']
32 
33 # itertools.compress()过滤数据
34 from itertools import compress
35 
36 
37 nums = [10,4,33,-54,54,-6,34,-5,23,56,-87,43,-4,3]
38 is_greater_than_0 = [i > 0 for i in nums] # 创建布尔值序列
39 print(is_greater_than_0)
40 # [True, True, True, False, True, False, True, False, True, True, False, True, False, True]
41 
42 print(list(compress(nums, is_greater_than_0))) # 为True的被保留,为False的被过滤
43 # [10, 4, 33, 54, 34, 23, 56, 43, 3]

 

 

参考资料:
  Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly). 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网