通過廖雪峯的Python2.7教程學習Python,此爲第一天。

本機Python版本是Python 2.7.5,系統平臺CentOS Linux release 7.2.1511 (Core)

爲避免中文字亂碼報錯,在文件首部添加# -*- coding: utf-8 -*-

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Simple Examples

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 100+200
300
>>> print 'Hello, world'
Hello, world
>>> exit()
[flying@lemp ~]$
  • 使用python進入Python交互模式
  • 使用print輸出字符串,可跟多個字串,使用逗號間隔
  • 使用exit()退出Python交互模式

.py文件首行添加

#!/usr/bin/env python

爲文件賦予執行權限後,即可直接執行文件

[flying@lemp PythonLearning]$ cat test/hello.py
#!/usr/bin/env python
print 'Hello, World!'
[flying@lemp PythonLearning]$ test/hello.py
Hello, World!
[flying@lemp PythonLearning]$
  • 進入Python交互模式,相當於啓動Python解釋器,輸入一行執行一行
  • 執行.py文件,相當於啓動Python解釋器,文件中代碼一次執行

Output

使用print輸出字符串,可跟多個字串,使用逗號間隔,輸出時將間隔符號轉換成空格

[flying@lemp PythonLearning]$ cat test/hello.py
#!/usr/bin/env python
print 'Hello, World!'
print 'Love','you','my','lover'
[flying@lemp PythonLearning]$ test/hello.py
Hello, World!
Love you my lover
[flying@lemp PythonLearning]$

print輸出整數

>>> 100+200
300
>>> print 100+200
300
>>> print '100+200=',100+200
100+200= 300
>>> print '100+200 =',100+200
100+200 = 300
>>>

Input

交互模式下,使用raw_input(),可將用戶輸入字符串存入其中,直接打印變量名即可輸出字符

>>> name = raw_input()
Lover
>>> name
'Lover'
>>> print name
Lover
>>> print 'Hello',name
Hello Lover
>>>

raw_input中寫入提示語

[flying@lemp PythonLearning]$ cat test/rawinput.py
#!/usr/bin/env python

name = raw_input('Please input your name: ')
print 'Hello',name,'!'
[flying@lemp PythonLearning]$ test/rawinput.py
Please input your name: lempstacker
Hello lempstacker !
[flying@lemp PythonLearning]$

Python Basics

在行首使用符號#進行註釋,Python解釋器自動忽視註釋語句不執行

Python採用縮進方式佈局代碼,縮進按四個空格

Python語言嚴格區分大小寫

Data Types & Variables

Data Types

  • interger: 包含正、負、0
  • float: 包含小數,數值過大可使用科學計數法,如1.23x10^9可寫成1.23e9
  • string:使用 單引號雙引號 包裹,如果需要字符串中包含單、雙引號,可使用反斜線\對其進行轉義,\本身使用\\進行轉義
  • boolean: 區分大小寫TrueFalse,二者可通過and, or, not進行與或非運算
  • NULL: 空值,使用None表示,區分大小寫
[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2

Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Lempstacker\'s Blog'
Lempstacker's Blog
>>> print 'Today is Sunday!\nIt\'s a sunny day!'
Today is Sunday!
It's a sunny day!
>>> exit()
[flying@lemp ~]$

使用r''表示引號中的字符串不轉義

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print '\\\n\\'
\
\
>>> print r'\\\n\\'
\\\n\\

>>> exit()
[flying@lemp ~]$

使用三個單引號'''...'''包裹,表示多行內容

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> print '''Lover
... you
... my
... lover'''
Lover
you
my
lover
>>> exit()
[flying@lemp ~]$

布爾運算

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True
True
>>> False
False
>>> True and True
True
>>> True or False
True

>>> not True
False
>>> 3 > 5
False
>>> 5 > 3
True
>>> exit()
[flying@lemp ~]$

Variables

  • constant: 常量如PI,全部使用大寫表示

變量,使用大小寫子母、數字、下劃線組合,不能用數字開頭。

定義變量無需使用符號$

通過符號=進行複製

因是動態語言,無需同時指定變量類型,同一變量名可重複使用。

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> print a
1
>>> b = 'character'
>>> print b
character
>>> c = True
>>> print c

True
>>> d = Null
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Null' is not defined
>>> c = 12345
>>> print c
12345
>>> exit()
[flying@lemp ~]$
[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 10
>>> print x
10
>>> x = x + 2
>>> print x
12
>>> x+=2
>>> print x

14
>>> x-=2
>>> print x
12
>>> x*=2
>>> print x
24
>>> x/=3
>>> print x
8
>>> exit()
[flying@lemp ~]$

String

字符串和編碼

Character Encode

字符編碼,UTF-8可變長編碼,英文子母佔用一個字節(byte),中文字佔用三個字節

爲避免中文字亂碼報錯,在文件首部添加# -*- coding: utf-8 -*-

#!/usr/bin/env python
# -*- coding: utf-8 -*-
[flying@lemp PythonLearning]$ cat test/china.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
name = raw_input('請輸入您的名字: ')
print '您的名字是:',name
[flying@lemp PythonLearning]$ python test/china.py
請輸入您的名字: lempstacker
您的名字是: lempstacker
[flying@lemp PythonLearning]$

Formatting

使用符號%格式化字符串 * %s: 表示字符串 * %d: 表示整數 * %f: 表示浮點數 * %x: 表示十六進制

使用方法與awk中類似

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'Today is %s, %4d-%2d-%2d.' % ('Sunday',2016,4,10)
'Today is Sunday, 2016- 4-10.'
>>> 'Today is %s, %4d-%-2d-%2d.' % ('Sunday',2016,4,10)
'Today is Sunday, 2016-4 -10.'
>>> 'Today is %10s, %4d-%-2d-%2d.' % ('Sunday',2016,4,10)
'Today is     Sunday, 2016-4 -10.'
>>> 'Today is %-10s, %4d-%-2d-%2d.' % ('Sunday',2016,4,10)

'Today is Sunday    , 2016-4 -10.'
>>> exit()
[flying@lemp ~]$

list & tuple

  • list: 數據列表,有序集合,可隨時添加或刪除其中元素

    • 使用方括號[]
    • 列表可以爲空
    • 元素下標以0開始
    • len()可獲取列表元素個數,最後一個元素位置len(list)-1,也可使用list[-1]獲取
    • append(element)可在列表後添加新元素
    • insert(pos,element)可在指定索引位置插入新元素
    • pop(pos),直接使用pop()可刪除最後一個元素,pop(pos)可刪除指定索引位置的元素
  • tuple: 與list類似,是數組,一旦初始化無法再更改(指向不變)

    • 因爲不可變,代碼更安全???
    • 定義只有一個元素的tuple時,可加逗號以消除歧義(()即可以表示tuple也可表示圓括號),如(1,)
    • 數據可以爲空

list

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> colour = ['red','green','blue','gray']
>>> colour
['red', 'green', 'blue', 'gray']
>>> len(colour)
4
>>> colour[0]
'red'
>>> colour[1]
'green'
>>> colour[-1]
'gray'
>>> colour.append('pink')
>>> colour
['red', 'green', 'blue', 'gray', 'pink']
>>> colour[2]
'blue'
>>> colour.insert(2,'purple')
>>> colour[2]
'purple'
>>> colour
['red', 'green', 'purple', 'blue', 'gray', 'pink']
>>> colour[-1]
'pink'
>>> colour.pop()
'pink'
>>> colour[-1]
'gray'
>>> colour
['red', 'green', 'purple', 'blue', 'gray']
>>> colour.pop(0)
'red'
>>> colour
['green', 'purple', 'blue', 'gray']
>>> colour[-1]
'gray'
>>> colour[-1] = 'orange'
>>> colour
['green', 'purple', 'blue', 'orange']
>>> L = []
>>> len(L)
0
>>> exit()
[flying@lemp ~]$

tuple

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> week = ('mon','tue','wed')
>>> week
('mon', 'tue', 'wed')
>>> week[0]
'mon'
>>> week[2]
'wed'
>>> week[-1]
'wed'
>>> tt = ()
>>> tt
()
>>> tt = (1)
>>> tt
1
>>> tt = (1,)
>>> tt
(1,)
>>> tt = ('a','b',['A','B'])
>>> tt[2][0] = 'X'
>>> tt[2][1] = 'Y'
>>> tt
('a', 'b', ['X', 'Y'])
>>> exit()
[flying@lemp ~]$

Condition & Loop

函數range(n)可生成n個從0開始的整數序列,0,1,2,...(num-1)

if

Python中,如果if語句判斷爲True,只執行縮進的語句。

if CONDITION1:
    OPERATION1
elif CONDITION2:
    OPERATION2
elif CONDITION3:
    OPERATION3
    ...
    ...
else:
    OPERATIONn

關鍵詞 if, elif, else

CONDITION後需要加冒號:else後也需要加冒號:

從上往下執行,遇到判斷是True的,就不會再往下執行。

測試1

#!/usr/bin/env python
# -*- coding: utf-8 -*-
weekday = ('Monday','Tuesday','Wensday','Thursday','Friday','Sataday','Sunday')
num = int(raw_input('Please input a num [1,7]: '))
if num > 7 or num < 1:
    print 'Error input'
else:
    print 'Your input is:',num,'\nWeekday is',weekday[num-1]
[flying@lemp test]$ python ifcondition.py
Please input a num [1,7]: 0
Error input
[flying@lemp test]$ python ifcondition.py
Please input a num [1,7]: 7
Your input is: 7
Weekday is Sunday
[flying@lemp test]$ python ifcondition.py
Please input a num [1,7]: 8
Error input
[flying@lemp test]$ python ifcondition.py
Please input a num [1,7]: 5
Your input is: 5
Weekday is Friday
[flying@lemp test]$

for loop

格式for...in...:,尾部有冒號:

#依次打印每一個元素
colour = ['red','green','blue','gray']
for i in colour:
    print i

測試1

#!/usr/bin/env python
# -*- coding: utf-8 -*-
weekday = ('Monday','Tuesday','Wensday','Thursday','Friday','Sataday','Sunday')
flag = 0
for i in weekday:
    flag+=1
    print 'Day',flag,':',i
[flying@lemp test]$ python for.py
Day 1 : Monday
Day 2 : Tuesday
Day 3 : Wensday
Day 4 : Thursday
Day 5 : Friday
Day 6 : Sataday
Day 7 : Sunday
[flying@lemp test]$

測試2

#!/usr/bin/env python
# -*- coding: utf-8 -*-

sum = 0
for i in range(101):
    sum += i
print sum

測試 九九乘法表

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# for i in range(9):
#     i+=1
#     for j in range(i):
#         j+=1
#         print i,'x',j,'=',i*j,'\t',
#     print '\n'


# for i in range(9):
#     i = 9 - i
#     for j in range(10-i):
#         j+=1
#         print i,'x',j,'=',i*j,'\t',
#     print '\n'


# for i in range(9):
#     i = 9 - i
#     for j in range(i):
#         j+=1
#         print j,'x',i,'=',i*j,'\t',
#     print '\n'

while loop

while CONDITION:
    OPERATION

raw_input()讀取的內容以字符串形式返回,如果輸入的是數值,可使用int(),但如果不是合法數字,int()會報錯。

測試1

#!/usr/bin/env python
# -*- coding: utf-8 -*-

flag = 0
total = 0
while flag < 100:
    flag+=1
    total+=flag
print 'Total is',total

測試九九乘法表

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# i = 1
# while i <= 9:
#     j = 1
#     while j <= i:
#         print i,'x',j,'=',i*j,'\t',
#         j+=1
#     print '\n'
#     i+=1

i = 9
while i > 0:
    j = 9
    while j >= i:
        print j,'x',i,'=',i*j,'\t',
        j-=1
    print '\n'
    i-=1

dict & set

dict類似於PHP中的關聯數組,以k-v形式存儲,其key必須是不可變對象

dict

dictionary,與list相比,dict查找和插入速度快,需要佔用大量內存。而list佔用空間和內存少,但是元素越多,插入和查找速度越快。

使用花括號{},key、val之間使用冒號:分隔,元素之間使用逗號,間隔

  • 可通過get(key)獲取對應key的val
  • 可通過pop(key)刪除對應key的val
[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> personinfo = {'name':'lemp','gender':'man','age':90}
>>> personinfo
{'gender': 'man', 'age': 90, 'name': 'lemp'}
>>> personinfo['gender']
'man'
>>> personinfo['age']
90

>>> personinfo['age'] = 20
>>> personinfo['age']
20
>>> personinfo
{'gender': 'man', 'age': 20, 'name': 'lemp'}
>>> personinfo.get('lemp')
>>> personinfo.get('name')
'lemp'
>>> personinfo.get('hobby','no this item')
'no this item'
>>> personinfo.pop('age')
20
>>> personinfo
{'gender': 'man', 'name': 'lemp'}
>>> exit()
[flying@lemp ~]$

set

set是一組key的集合,元素惟一、無序 (類數學中的集合)

用圓括號間隔()

  • 通過add(key)添加元素
  • 通過remove(key)刪除元素

創建set,須用list作爲輸入集合

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> num = set([1,1,2,3,4,5,5,5,6])
>>> num
set([1, 2, 3, 4, 5, 6])
>>> num.add(7)
>>> num
set([1, 2, 3, 4, 5, 6, 7])
>>> num.remove(5)
>>> num
set([1, 2, 3, 4, 6, 7])
>>> s1 = set([1,2,3,4])
>>> s2 = set([2,3,4,5,6])
>>> s1 & s2
set([2, 3, 4])
>>> s1 | s2
set([1, 2, 3, 4, 5, 6])
>>> alpha = ['g','b','e','f']
>>> alpha.sort()
>>> alpha
['b', 'e', 'f', 'g']
>>> alpha = 'abcdef'
>>> alpha
'abcdef'
>>> alpha.replace('b','B')
'aBcdef'
>>> alpha
'abcdef'
>>> exit()
[flying@lemp ~]$

對於以下結果,可使用Shell中的管道符|來理解,處理的是輸出

>>> alpha = 'abcdef'
>>> alpha
'abcdef'
>>> alpha.replace('b','B')
'aBcdef'
>>> alpha
'abcdef'

Function

調用函數需要知道函數的 名稱參數

  • abs():絕對值
  • cmp(x,y): x>y返回1,x<y返回-1,x=y返回0
  • int(): 轉換成整型
  • float(): 轉換成浮點型
  • str(): 轉換成字符串
  • unicode(): 轉換成unicode字符
  • bool(): 布爾判斷

函數可賦給變量,作爲變量別名

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> abs(-20)
20
>>> abs(12)
12
>>> abs(12,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)
>>> abs(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> cmp(1,2)
-1
>>> cmp(2,1)
1
>>> cmp(2,2)
0
>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> unicode(100)
u'100'
>>> bool(1)
True
>>> bool('')
False
>>> a = abs
>>> a(-80)
80
>>> exit()
[flying@lemp ~]$

Define Function

使用def定義函數

定義函數須確定 函數名參數個數

如果有必要,可對參數數據類型做檢查

函數體內可使用return返回函數結果

函數執行完畢沒發現有return語句,自動return None

函數可同時返回多個值,其實是tuple(數組)

可使用isinstance()對數據類型進行檢查

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x

print my_abs(-9)

pass可作爲佔爲符,爲代碼段佔位,保持程序結構的完整性,確保不會出現語法錯誤

def nop():
    pass

print nop()

可使用isinstance()對數據類型進行檢查

def my_abs(x):
    if not isinstance(x,(int,float)):
        raise TypeError('Error Data Type')
    if x >= 0:
        return x
    else:
        return -x
print my_abs(dsf)
[flying@lemp test]$ python function.py
Traceback (most recent call last):
  File "function.py", line 11, in <module>
    print my_abs(dsf)
NameError: name 'dsf' is not defined
[flying@lemp test]$

函數參數也可定義默認參數,當參數缺省時調用

def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

函數有多個參數時,建議將變化頻繁的參數放置在前面,較低函數調用的難度

  • 可變參數
def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

調用時,組裝listtuple

calc([1,2,3]) 可寫成 calc(1,2,3)
calc((1,3,5,7)) 可寫成 calc(1,3,5,7)

使用符號*定義 可變 參數,可傳入0個或多個參數,在調用是自動組裝成tuple

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

使用符號**定義 *關鍵字參數*,在調用時自動組裝成dict(關聯數組)

[flying@lemp test]$ cat keypara.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

def person(name,age,**kw):
    print 'name:', name, 'age:', age, 'other:', kw

person('lemp',30,city='Beijing')
[flying@lemp test]$ python keypara.py
name: lemp age: 30 other: {'city': 'Beijing'}
[flying@lemp test]$
person('lemp',30,gender='male',city='Beijing')

[flying@lemp test]$ python keypara.py
name: lemp age: 30 other: {'gender': 'male', 'city': 'Beijing
'}
[flying@lemp test]$
def func(a, b, c=0, *args, **kw):
    print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw


>>> func(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> func(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> func(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
>>> func(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}

默認參數須時不可變對象

  • *agrs是可變參數,接收的是tuple
  • **kw是關鍵字參數,接收的是dict
以及调用函数时如何传入可变参数和关键字参数的语法:

可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过*args传入:func(*(1, 2, 3));

关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过**kw传入:func(**{'a': 1, 'b': 2})。

Recursive Function

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def recursive(n):
    if not isinstance (n,(int)):
        raise TypeError('Error Data Type')
    if n==1:
        return 1
    return n * recursive(n-1)

print recursive(5)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

L = []
n = 1
while n <= 99:
    L.append(n)
    n+=9
print L
[flying@lemp test]$ python increase.py
[1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91]
[flying@lemp test]$

Slice

slice切片,類似於字符截取函數

從某索引開始,到某索引截止,但不包括該索引

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> weekday = ['Monday','Tuesday','Wensday','Thursday','Friday','Sataday','Sunday']
>>> weekday
['Monday', 'Tuesday', 'Wensday', 'Thursday', 'Friday', 'Sataday', 'Sunday']
>>> weekday[:3]
['Monday', 'Tuesday', 'Wensday']
>>> weekday[-2:]
['Sataday', 'Sunday']
>>> weekday[1:2]
['Tuesday']
>>> weekday[1:3]
['Tuesday', 'Wensday']
>>> weekday[1:6:2]
['Tuesday', 'Thursday', 'Sataday']
>>> weekday[:]
['Monday', 'Tuesday', 'Wensday', 'Thursday', 'Friday', 'Sataday', 'Sunday']
>>> exit()
[flying@lemp ~]$

迭代(iteration)

使用for k, v in d.iteritems()進行迭代,類似於PHP中的foreach ($arr as $key=>$val)

[flying@lemp ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
...     print key
...
a
c
b
>>> for key in d.iteritems():
...     print key
...
('a', 1)
('c', 3)
('b', 2)
>>> for key,val in d.iteritems():
...     print key,val
...
a 1
c 3
b 2
>>> exit()
[flying@lemp ~]$

列表生成式

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>> L = []
>>> for i in range(1,11):
...     L.append(i * i)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> exit()
>>> [i * i for i in range(1,11) if i % 2 == 0]
[4, 16, 36, 64, 100]
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
>>> import os
>>> [d for d in os.listdir('/home/flying/PythonLearning/test')]
['hello.py', 'rawinput.py', 'china.py', 'ifcondition.py', 'for.py', 'while.py', 'function.py', 'keypara.py', 'recursive.py', 'increase.py']
>>>
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k,v in d.iteritems():
...     print k,'=',v
...
y = B
x = A
z = C
>>>
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.iteritems()]
['y=B', 'x=A', 'z=C']
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
>>> [s.upper() for s in L]
['HELLO', 'WORLD', 'IBM', 'APPLE']
>>>

Generator

生成器:一邊循環一邊計算


  • Note Time: 2016.04.10 22:06 Sun
  • Note Location: Asia/Beijing
  • Writer: lempstacker