python list.remove(),del()和filter & lambda

來源:互聯網
上載者:User

標籤:

面試題之一。

以下代碼能運行嗎?

l = [1,2,3,4,5]for i in range(0,len(l)):    print i    if l[i] % 2 == 0:        del l[i]print l
結果:
Traceback (most recent call last):  File "D:\1.py", line 3, in <module>    if l[i] % 2 == 0:IndexError: list index out of range

啊,因為隨著del()語句的執行,list的元素越來越少,但是for已經定了[0,5):

i = 0,l[i] = 1不是偶數跳過

i = 1,l[i] = 2是偶數,l = [1,3,4,5]

i = 2,l[i] = 4是偶數,l=[1,3,5]

i = 3,l[i] 越界了,list index out of range。

 



以下代碼能運行嗎?

ll = [1,2,3,4,5]for i in ll:    if i % 2 == 0:        ll.remove(i)print ll
結果:

>>> [1, 3, 5]>>> 
啊,這段代碼就沒上述的問題。list有多少就取多少。




用filter()和lambda實現上面的功能:

print filter(lambda e:e%2!=0,ll)
結果:

>>> [1, 3, 5]>>> 
啊,就這麼簡單。




說下filter()吧:

filter(function,list),把list中的元素一個個丟到function中,Return True的元素組成一個new list。

ll = [1,2,3,4,5]def func(x):    return x % 2 != 0print filter(func,ll)



說下lambda吧:

匿名函數,lambda a:b,其中a表示參數,b表示返回值。

上面就是lambda e : e%2 != 0 。




總結:

1、迴圈list的時候,最好用for i in list:,減少因為del()放下不易察覺的失誤。

2、沒事用用filter()和lambda,感覺挺裝逼的。(這算什麼總結嘛。)










著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

python list.remove(),del()和filter & lambda

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.