99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python列表生成式12個(gè)小功能,你常用哪幾個(gè)?
Python列表生成式12個(gè)小功能,你常用哪幾個(gè)?
2019-11-27
收藏
Python列表生成式12個(gè)小功能,你常用哪幾個(gè)?

作者 | zglg

來源 | Python與算法社區(qū)

python里[] 表示一個(gè)列表,對容器類型的數(shù)據(jù)進(jìn)行運(yùn)算和操作,生成新的列表最高效、快速的辦法,就是列表生成式。

它優(yōu)雅、簡潔,值得大家多多使用!今天盤點(diǎn)列表生成式在工作中的主要使用場景。

入門

1

range快速生成連續(xù)列表

In [1]: a = range(11)
In [2]: a
Out[2]: range(0, 11)
In [3]: list(a)
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2

對列表里面的數(shù)據(jù)進(jìn)行運(yùn)算后重新生成一個(gè)新的列表:

In [5]: a = range(0,11)
In [6]: b = [x**2 for x in a]
In [7]: b
Out[7]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3

對一個(gè)列表里面的數(shù)據(jù)篩選,只計(jì)算[0,11) 中偶數(shù)的平方:

In [10]: a = range(11)
In [11]: c = [x**2 for x in a if x%2==0]
In [12]: c
Out[12]: [0, 4, 16, 36, 64, 100]

4

前面列表生成式都只傳一個(gè)參數(shù)x,帶有兩個(gè)參數(shù)的運(yùn)算:

In [13]: a = range(5)
In [14]: b = ['a','b','c','d','e']
In [20]: c = [str(y) + str(x) for x, y in zip(a,b)]
In [21]: c
Out[21]: ['a0', 'b1', 'c2', 'd3', 'e4']

5

結(jié)合字典,打印鍵值對:

In [22]: a = {'a':1,'b':2,'c':3}
In [23]: b = [k+ '=' + v for k, v in a.items()]
In [24]: b = [k+ '=' + str(v) for k, v in a.items()]
In [25]: b
Out[25]: ['a=1', 'b=2', 'c=3']

6

輸出某個(gè)目錄下的所有文件和文件夾的名稱:

In [33]: [d for d in os.listdir('d:/summary')]

Out[33]: ['a.txt.txt', 'python-100']

7

列表中所有單詞都轉(zhuǎn)化為小寫:

In [34]: a = ['Hello', 'World', '2019Python']
In [35]: [w.lower() for w in a]
Out[35]: ['hello', 'world', '2019python']
Python列表生成式12個(gè)小功能,你常用哪幾個(gè)?

進(jìn)階

8

將值分組:

In [36]: def bifurcate(lst, filter):
 ...: return [
 ...: [x for i,x in enumerate(lst) if filter[i] == True],
 ...: [x for i,x in enumerate(lst) if filter[i] == False]
 ...: ]
 ...:
In [37]: bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])
Out[37]: [['beep', 'boop', 'bar'], ['foo']]

9

進(jìn)一步抽象例子8,根據(jù)指定函數(shù)fn 對lst 分組:

In [38]: def bifurcate_by(lst, fn):
 ...: return [
 ...: [x for x in lst if fn(x)],
 ...: [x for x in lst if not fn(x)]
 ...: ]
 ...:
In [39]: bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
Out[39]: [['beep', 'boop', 'bar'], ['foo']]

10

返回可迭代對象的差集,注意首先都把a(bǔ), b用set 包裝

In [53]: def difference(a, b):

...: _a, _b =set(a),set(b)

...: return [item for item in _a if item not in _b]

...:

...:

In [54]: difference([1,1,2,3,3], [1, 2, 4])

Out[54]: [3]

11

進(jìn)一步抽象10,根據(jù)函數(shù)fn 映射后選取差集,如下列表元素分別為單個(gè)元素和字典的例子:

In [61]: def difference_by(a, b, fn):

...: ...: _b = set(map(fn, b))

...: ...: return [item for item in a if fn(item) not in _b]

...: ...:

...:

In [62]: from math import floor

...: difference_by([2.1, 1.2], [2.3, 3.4],floor)

Out[62]: [1.2]

In [63]: difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x'])

Out[63]: [{'x': 2}]

12

過濾非重復(fù)值,結(jié)合list 的count( 統(tǒng)計(jì)出元素在列表中出現(xiàn)次數(shù)):

In [64]: def filter_non_unique(lst):
 ...: return [item for item in lst if lst.count(item) == 1]
In [65]: filter_non_unique([1, 2, 2, 3, 4, 4, 5])
Out[65]: [1, 3, 5]

熟練操作以上12個(gè)例子,就算掌握python 中非常有用的列表生成式。

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }