python中for...if...構建List

來源:互聯網
上載者:User

標籤:for   一個   log   lis   組成   logs   str   class   簡單   

1.簡單的for...[if]...語句

>>> a=[12, 3, 4, 6, 7, 13, 21]>>> newList = [x for x in a]>>> newList[12, 3, 4, 6, 7, 13, 21]>>> newList2 = [x for x in a if x%2==0]>>> newList2[12, 4, 6]

newList構建了一個與a具有相同元素的List。但是,newList和a是不同的List。執行b=a,b和newList是不同的。

newList2是從a中選取滿足x%2==0的元素組成的List。

 

2.嵌套的for...[if]...語句

嵌套的for...[if]...語句可以從多個List中選擇滿足if條件的元素組成新的List。下面也舉幾個例子。

>>>a=[12, 3, 4, 6, 7, 13, 21]>>>b=[‘a‘, ‘b‘, ‘x‘]>>>newList=[(x, y) for x in a for y in b]>>>newList[(12, ‘a‘), (12, ‘b‘), (12, ‘x‘), (3, ‘a‘), (3, ‘b‘), (3, ‘x‘), (4, ‘a‘), (4, ‘b‘), (4, ‘x‘), (6, ‘a‘), (6, ‘b‘), (6, ‘x‘), (7, ‘a‘), (7, ‘b‘), (7, ‘x‘), (13, ‘a‘), (13, ‘b‘), (13, ‘x‘), (21, ‘a‘), (21, ‘b‘), (21, ‘x‘)]>>>newList2=[(x, y) for x in a for y in b if x%2==0 and y<‘x‘]>>>newList2[(12, ‘a‘), (12, ‘b‘), (4, ‘a‘), (4, ‘b‘), (6, ‘a‘), (6, ‘b‘)]

  

python中for...if...構建List

聯繫我們

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