List generator used to filter the packet list (enumeration method and the body function method)

Element number acquired by the enumerate, then the Boolean value obtained by the filter ID, then according to the Boolean value as a determination condition, the list elements of the same formula of the type taken out. code show as below:

lst = ['beep','boop','foo','bar']
filters = [True,False,False,True]

def bifurcate(lst,filters):
	return [
		[ x for i,x in enumerate(lst) if filters[i]==True],
		[ x for i,x in enumerate(lst) if filters[i]==False]
	]

print(bifurcate(lst,filters))

Output:

[['beep', 'bar'], ['boop', 'foo']]
[Finished in 0.6s]

We can also use the function method to implement filtering capabilities, as long as attention is the core of our judgment there is a Boolean expression for the if statement.

def bifurcate(lst,fn):
	return[
		[ x for x in lst if fn(x)],
		[ x for x in lst if not fn(x)]
	]

lst = ['up','Python','umbrella','allan']
results = bifurcate(lst, lambda x: x[0] == 'u')
print(results)

Output is as follows:

[['up', 'umbrella'], ['Python', 'allan']]
[Finished in 0.6s]
Published 170 original articles · won praise 9 · views 4542

Guess you like

Origin blog.csdn.net/weixin_41855010/article/details/104483116