Python學習九:列表產生式

來源:互聯網
上載者:User

標籤:學習   ber   tps   字元   net   led   inf   copyto   c++   

 2015年02月12日 15:38:52閱讀數:32624

列表產生式,是Python內建的一種極其強大的產生list的運算式。

如果要產生一個list [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9] 可以用 range(1 , 10):

 

[python] view plain copy 
  1. >>> range(1, 9)  
  2. [1, 2, 3, 4, 5, 6, 7, 8]  

可是,如果要產生[1*1 , 2*2 , 3*3 , ... , 10*10] 怎麼做呢?可以使用迴圈:

 

[python] view plain copy 
  1. >>> L= []  
  2. >>> for x in range(1 , 10):  
  3. ...     L.append(x*x)  
  4. ...   
  5. >>> L  
  6. [1, 4, 9, 16, 25, 36, 49, 64, 81]  

而列表產生式,可以用一句代替以上的繁瑣迴圈來完成上面的操作:

 

[python] view plain copy 
  1. >>> print [x*x for x in range(1 , 11)]  
  2. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]  
  3. >>>   

列表產生式的書寫格式:[x*x for x in range(1 , 11)]

第一:把要產生的元素 x*x 放到前面

第二:後面跟上for迴圈

這樣就可以把list建立出來。

for迴圈後面還可以加上if判斷,這樣可以篩選出偶數的平方:

 

[python] view plain copy 
  1. >>> [x*x for x in range(1 , 11) if x%2 == 0]  
  2. [4, 16, 36, 64, 100]  
  3. >>>   

當然,可以使用兩層迴圈,產生全排列:

 

[python] view plain copy 
  1. >>> print [m + n for m in ‘ABCD‘ for n in ‘XYZ‘]  
  2. [‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘, ‘DX‘, ‘DY‘, ‘DZ‘]  
  3. >>>   
如何使用兩個變數來產生list:

 

[python] view plain copy 
  1. d = {‘Java‘:"99" , ‘C‘:"99" , ‘C++‘:"99" }  
  2. L = [k+‘=‘+v for k , v in d.iteritems()]  
  3.   
  4. print L  

最後來做一個練習:

L = [‘Java‘ , ‘C‘ , ‘Swift‘ , ‘Python‘ , 123] , 現在有 list 中包含字串,和整數,把list中得大寫字元轉為小寫,推到出另外一個list":

1、使用內建的isinstance函數可以判斷一個變數是不是字串

2、s.lower() 可以將一個大寫字母轉為小寫。

3、增加if語句保證列表產生式正確執行。

代碼如下:

 

[python] view plain copy 
  1. L = [‘Java‘ , ‘C‘ , ‘Swift‘ , ‘Python‘ , 123]  
  2. print [s.lower() if isinstance(s , str) else s for s in L ]  


Python學習九:列表產生式

聯繫我們

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