python3 中的 map,reduce,filter函數

來源:互聯網
上載者:User

在python2 中直接列印map,filter函數會直接輸出結果。但在python3中做了些修改,輸出前需要使用list()進行顯示轉換,而reduce函數則被放到了functools包中,代碼如下

from functools import reduceimport mathdef format_name(s):    return s.upper()def is_odd(x):    return x % 2 == 1def sqr_integer(x):    r = math.floor(math.sqrt(x))    return x == r*rdef f(x, y):    return x + y# map 把函數 f 依次作用在 list 的每個元素上,得到一個 iterator  並返回。print(list(map(format_name, ['adam', 'LISA', 'barT'])))# reduce()傳入的函數 f 必須接收兩個參數,reduce()對list的每個元素反覆調用函數f,並返回最終結果值。reduce()還可以接收第3個選擇性參數,作為計算的初始值。print(reduce(f, [1, 3, 5, 7, 9], 100))# filter()根據判斷結果自動過濾掉不合格元素,返回由符合條件元素組成的iterator。print(list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17])))print(list(filter(sqr_integer,range(100))))

運行結果如下

['ADAM', 'LISA', 'BART']125[1, 7, 9, 17][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.