python中利用boolean list檢索list的方法

問題如下:

numbers = [1, 0, 2, 4]
bools = [True, False, False, True]
result = [1, 4]

通過numbers和bools獲取result.

方法一:

[number for number, b in zip(numbers, bools) if b == True]

方法二:

np.array(numbers)[np.array(bools)]

方法三:

from itertools import compress 

list(compress(numbers, bools)) 

https://www.geeksforgeeks.org/python-filter-list-by-boolean-list/

https://stackoverflow.com/questions/41762592/selection-elements-of-a-list-based-on-another-true-false-list

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章