Python:filter(None,[list of bools])行为

时间:2016-07-12 21:56:44

标签: python

编辑:在阅读建议的链接后,我不知道为什么这被标记为重复。起诉我。

任何人都可以帮助我理解filter(None, [list of bools])删除False值的原因吗?

采取以下措施:

low = 25 
high = 35
to_match = [15, 30, 32, 99]
def check(low, high, to_match):
    return [low <= i <= high for i in to_match]

check(low, high, to_match)返回[False, True, True, False]

filter(None, check(low, high, to_match))返回[True, True]

所以我想,Python必须认为FalseNone!但令我惊讶的是,False is None会返回False

A)我错过了什么?

B)如何仅从None过滤[True, None, False]个值?

2 个答案:

答案 0 :(得分:11)

如果您要过滤掉None,请使用:

filter(lambda x: x is not None, [list of bools])

[x for x in [list of bools] if x is not None]

filter takes a function, not a valuefilter(None, ...)filter(lambda x: x, ...)的简写 - 它会过滤掉false-y的值(强调我的):

  

filter(function, iterable)

     

根据iterablefunction返回true的元素构造一个列表。 iterable可以是序列,支持迭代的容器,也可以是迭代器。如果iterable是字符串或元组,则结果也具有该类型;否则它总是一个列表。 如果函数为None,则假定使用标识函数,即删除iterable中所有为false的元素。

     

请注意,如果函数不是filter(function, iterable),则[item for item in iterable if function(item)]等同于None,如果函数是[item for item in iterable if item],则None等同于package main import ( "bytes" "encoding/json" "fmt" "net/http" ) var ThirdPartyApi = "http://www.coolsongssite.api" type IncomingRequest struct { username string `json:"username"` password string `json:"password"` songs []IncomingSong `json:"songs"` } type OutgoingRequest struct { username string `json:"username"` password string `json:"password"` songs []OutgoingSong `json:"songs"` } type IncomingSong struct { artist string `json:"artist"` album string `json:"album"` title string `json:"title"` } type OutgoingSong struct { musician string `json:"musician"` record string `json:"record"` name string `json:"name"` } func main() { http.HandleFunc("/songs/create", createSong) http.ListenAndServe(":8080", nil) } func createSong(rw http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) var incomingRequest IncomingRequest decoder.Decode(&incomingRequest) outgoingRequest := incomingRequestToOutgoingRequest(incomingRequest) r, _ := json.Marshal(outgoingRequest) request, _ := http.NewRequest("POST", ThirdPartyApi, bytes.NewBuffer(r)) request.Header.Set("Content-Type", "application/json") client := http.Client{} response, _ := client.Do(request) fmt.Fprintln(rw, response) } func incomingRequestToOutgoingRequest(inc IncomingRequest) OutgoingRequest { outgoingRequest := OutgoingRequest{ username: inc.username, password: inc.password, } for _, s := range inc.songs { outgoingRequest.songs = append( outgoingRequest.songs, OutgoingSong{ musician: s.artist, record: s.album, name: s.title, }, ) } return outgoingRequest }

答案 1 :(得分:5)

对于python3,您可以使用None.__ne__仅删除None,只使用None过滤将删除任何虚假值,如[], {} 0等。:

filter(None.__ne__, check(low, high, to_match))

对于python2,您需要添加一个lambda来检查每个元素is not None

filter(lambda x: x is not None,....)

如果您正在使用python2,请坚持列表comp:

[ele for ele in check(low, high, match) if ele is not None]

使用过滤器的任何性能提升都会被lambda调用所抵消,所以它实际上会慢一些。