Files
2025-09-10 16:12:45 +08:00

72 lines
2.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 比如我有一个列表
mylist = [1,4,-5,10,-7,2,3,-1]
# 最脑瘫的方法就是用列表推导式重新生成一遍
filted_list_b0 = [x for x in mylist if x > 0]
filted_list_s0 = [x for x in mylist if x < 0]
# print(filted_list_b0)
# 当然如果列表很大这样做会裂开因为列表推导式本质上是遍历会建立一份mylist的复制
# 这个时候我们可以用生成器的方式表达解析结果以节省内存
filted_list_b0 = (x for x in mylist if x > 0)
# for i in filted_list_b0:
# print(i)
# 当然有的列表比较抽象:
mylist_suka = ['1', '2', '-3', '-', '4', 'N\A', '5']
# 这个时候我们可以先写逻辑进行过滤:
def drop_suka(val):
try:
x = int(val)
return True
except ValueError:
return False
# 然后我们用内建的filter函数进行过滤
# 第一个位置是一个值判断布尔函数,第二个参数是要过滤的列表,布尔函数里写过滤逻辑;
# filter返回一个迭代器所以可以直接用list方法转成列表
my_nonsuka_list = list(filter(drop_suka, mylist_suka))
# print(my_nonsuka_list)
# 列表推导式和生成器推导式都可以在值的位置进行:
# 1.计算 x*2
# 2.三元判断 x*2 if x < 1 else x
filted_list_b0 = [x*2 if x < 1 else x for x in mylist if x > 0]
filted_list_b0 = (x*2 if x < 1 else x for x in mylist if x > 0)
# 如果要筛选的元素在另一个列表里怎么办?比如我们有:
rows = [
"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]
# counts表示rows里面对应元素出现的次数如果我们想找count>5的元素咋整
# 1.搞一个布尔列表,告诉程序谁才是我们要的
wanted = [n > 5 for n in counts] # 这和[n for n in counts if n > 5]不一样,之前是在for的同时筛选,现在是for完看看是否符合n>5
# print(wanted)
# 2.用itertools的compress函数来进行对比
from itertools import compress
# itertools里的compress函数输入一个列表和一个布尔列表,返回一个迭代器,里面是列表中同样位置在布尔列表里为True的元素
result = list(compress(rows, wanted))
print(result)