python List Comprehensions(列表產生式)

來源:互聯網
上載者:User

標籤:技術   convert   大寫   port   ring   size   type   pytho   os模組   

列表產生式: 建立List

普通建立List格式:

    1.定義List變數

    2.for .. in ..:

            語句;


列表產生式List格式:

    [ 語句 for .. in ..]


可見,列表產生式只不過是將for裡的語句提到for的同行之前而已。        


一、普通建立List

#!/usr/bin/python

#common establish way
lis1 = [];
for x in range(1, 10):
    lis1.append(x);
print "lis1:", lis1;


二、列表產生式

#List comprehensions
lis2 = [x for x in range(1, 10)]
print "lis2:", lis2;


#also can choose the even number in list
lis3 = [x * x for x in range(1, 10) if x%2 == 0]
print "lis3:", lis3;


#two for in list
lis4 = [x + y for x in 'ABC' for y in 'XYZ']
print "lis4:", lis4;


#show the file in directory
import os;     #匯入OS模組
lis5 = [d for d in os.listdir('.')]
print lis5;


#convert all big_write string to small_write
L = ['ABC', 'EFG', 'Hij', '8']   #只能為char類型,其他類型提示出錯
lis6 = [s.lower() for s in L]   #lower()是內建函數,將大寫轉為小寫
print lis6;


python List Comprehensions(列表產生式)

相關文章

聯繫我們

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