1. 程式人生 > >python3.6.4的學習

python3.6.4的學習

python3.6

[root@mantisbt01 python]# ./13.py
Please input your name:hadoop
Please input your height(m):1.80
Please input your height(kg):75.3
hadoop , Your bmi value is: 23.24 !
Your body type is 正常
[root@mantisbt01 python]# python
Python 3.6.4 (default, Mar 19 2018, 10:30:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>> abs(12)
12
>> abs(-12)
12
>> abs(0)
0
>> abs(-12.3)
12.3
>> abs(12.3)
12.3
>> abs(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)
>> abs(f)
Traceback (most recent call last):

File "<stdin>", line 1, in <module>
NameError: name ‘f‘ is not defined
>> max(1,2)
2
>> max(1,2,23,4)
23
>> max(1,2,23,4,-9,0)
23
>> int(321)
321
>> int(12.32)
12
>> float(12.32)
12.32
>> float(12)
12.0
>> float(‘12.32‘)
12.32
>> str(100)
‘100‘
>> str(13)
‘13‘
>> str(as)
File "<stdin>", line 1
str(as)
^
SyntaxError: invalid syntax
>> str(‘as‘)
‘as‘
>> str(‘a‘)
‘a‘
>> str(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘a‘ is not defined
>> bool(1)
True
>> bool(-1)
True
>> bool(0)
False
>> bool(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘a‘ is not defined
>> bool(‘a‘)
True
>> a=abs
>> a(-2)
2
>> n1=255
>> n2=1000
>> hex(n1)
‘0xff‘
>> hex(n2)
‘0x3e8‘

>> def my_abs(x):
... if x >=0:
... return x
... else:
... return -x
...
>> my_abs(-9)
9
>> my_abs(-8)
8
>> my_abs(8)
8
>> my_abs(0)
0
>> my_abs(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in my_abs
TypeError: ‘>=‘ not supported between instances of ‘builtin_function_or_method‘ and ‘int‘
>> my_abs(‘a‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in my_abs
TypeError: ‘>=‘ not supported between instances of ‘str‘ and ‘int‘
>>

[root@mantisbt01 python]# pwd
/root/python
[root@mantisbt01 python]# cat 14.py
def my_abs(x):
if x >=0:
return x
else:
return -x
[root@mantisbt01 python]# python
Python 3.6.4 (default, Mar 19 2018, 10:30:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>> from 14 import my_abs
File "<stdin>", line 1
from 14 import my_abs
^
SyntaxError: invalid syntax
>>
KeyboardInterrupt
>>
[root@mantisbt01 python]# mv 14.py abstest.py
[root@mantisbt01 python]# python
Python 3.6.4 (default, Mar 19 2018, 10:30:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>> from abstest import my_abs
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/root/python/abstest.py", line 3
return x
^
TabError: inconsistent use of tabs and spaces in indentation
>>
[root@mantisbt01 python]# vi abstest.py
[root@mantisbt01 python]# python
Python 3.6.4 (default, Mar 19 2018, 10:30:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>> from abstest import my_abs
>> my_abs(-18)
18
>> my_abs(19)
19
>> my_abs(0)
0
>> my_abs(‘a‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/root/python/abstest.py", line 2, in my_abs
if x >=0:
TypeError: ‘>=‘ not supported between instances of ‘str‘ and ‘int‘
>> my_abs(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘a‘ is not defined
>>
>> def nop():
... pass
...
>>
>> if age >=18:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘age‘ is not defined
>> age=10
>> if age >=18:
... age
...
>>
>> my_abs(2)
2
>> my_abs(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_abs() takes 1 positional argument but 2 were given
>> my_abs(‘A‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/root/python/abstest.py", line 2, in my_abs
if x >=0:
TypeError: ‘>=‘ not supported between instances of ‘str‘ and ‘int‘
>> abs(‘A‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): ‘str‘
>>
[root@mantisbt01 python]# cp -p abstest.py abstest2.py
[root@mantisbt01 python]#
[root@mantisbt01 python]# vi abstest2.py
[root@mantisbt01 python]# cat abstest2.py
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError(‘bad operand type‘)
if x >=0:
return x
else:
return -x
[root@mantisbt01 python]#

[root@mantisbt01 python]# cp -p abstest.py abstest2.py
[root@mantisbt01 python]#
[root@mantisbt01 python]# vi abstest2.py
[root@mantisbt01 python]# cat abstest2.py
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError(‘bad operand type‘)
if x >=0:
return x
else:
return -x
[root@mantisbt01 python]# python
Python 3.6.4 (default, Mar 19 2018, 10:30:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>> from abstest2 import my_abs
>> my_abs(-9)
9
>> my_abs(9)
9
>> my_abs(0)
0
>> my_abs(‘A‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/root/python/abstest2.py", line 3, in my_abs
raise TypeError(‘bad operand type‘)
TypeError: bad operand type
>>

>> import math
>> def move(x,y,step,angle=0):
... nx = x + step math.cos(angle)
... ny = y + step
math.sin(angle)
... return nx,ny
...
>> x,y=move(100,100,60,math.pi / 6)
>> print(x,y)
151.96152422706632 130.0
>> r = move(100,100,60,math.pi / 6)
>> print(r)
(151.96152422706632, 130.0)
>>

>> r
(151.96152422706632, 130.0)
>>

[root@mantisbt01 python]# cat 14.py
#!/usr/bin/python

#-- coding: utf-8 --

import math
def quadratic(a,b,c):
if not ( isinstance(a,(int,float)) and isinstance(b,(int,float)) and isinstance(c,(int,float)) ):
raise TypeError(‘bad operand type‘)
delta=(b*2)-(4bc)
if delta < 0:
print(‘delta小於零,方程無解‘)
else:
x1=(-b+math.sqrt(delta))/(2
a)
x2=(-b-math.sqrt(delta))/(2*a)
print(‘x1=%.2f x2=%.2f‘%(x1,x2))
return x1,x2

print(‘quadratic(2,3,1)=‘,quadratic(2,3,1))
print(‘quadratic(1,3,-4)=‘,quadratic(1,3,-4))
[root@mantisbt01 python]# ./14.py
delta小於零,方程無解
quadratic(2,3,1)= None
x1=2.27 x2=-5.27
quadratic(1,3,-4)= (2.274917217635375, -5.274917217635375)
[root@mantisbt01 python]#

>> def power(x):
... return x*x
...
>> power(4)
16
>> power(2)
4
>> power(3)
9
>> power(11)
121

>> def power(x,n)
File "<stdin>", line 1
def power(x,n)
^
SyntaxError: invalid syntax
>> def power(x,n):
... s=1
... while n > 0:
... n=n-1
... s=s*x
... return s
...
>> power(2,3)
8
>> power(3,3)
27
>> power(3,4)
81
>>

>> power(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: power() missing 1 required positional argument: ‘n‘
>> def power(x,n=2):
... s=1
... while n > 0:
... n=n-1
... s=sx
... return
...
>> power(5)
>> def power(x,n=2):
... s=1
... while n > 0:
... n=n-1
... s=s
x
... return s
...
>> power(5)
25
>> power(3)
9
>> power(3,4)
81
>>

>> def enroll(name,gender):
... print(‘name:‘,name)
... print(‘gender:‘,gender)
...
>> enroll(‘Sarah‘,‘F‘)
name: Sarah
gender: F
>> def enroll(name,gender,age=6,city=‘Beijing‘):
... print(‘name:‘,name)
... print(‘gender‘,gender)
... print(‘age:‘,age)
... print(‘city:‘,city)
...
>>
>> enroll(‘Sarah‘,‘F‘)
name: Sarah
gender F
age: 6
city: Beijing
>> enroll(‘Bob‘,‘M‘,8)
name: Bob
gender M
age: 8
city: Beijing
>> enroll(‘Adam‘,‘M‘,city=‘shanghai‘)
name: Adam
gender M
age: 6
city: shanghai

>> def add_end(L=[]):
... L.append(‘END‘)
... return L
...
>> add_end([1,2,3])
[1, 2, 3, ‘END‘]
>> add_end([‘x‘,‘y‘,‘z‘])
[‘x‘, ‘y‘, ‘z‘, ‘END‘]
>> add_end([1,2,3])
[1, 2, 3, ‘END‘]
>> add_end()
[‘END‘]
>> add_end()
[‘END‘, ‘END‘]
>> add_end()
[‘END‘, ‘END‘, ‘END‘]
>> add_end()
[‘END‘, ‘END‘, ‘END‘, ‘END‘]
>> def add_end(L=[]):
... if L is None:
... L=[]
... L.append(‘END‘)
... return L
...
>> add_end()
[‘END‘]
>> add_end()
[‘END‘, ‘END‘]
>> add_end()
[‘END‘, ‘END‘, ‘END‘]
>> def add_end(L=None):
... if L is None:
... L=[]
... L.append(‘END‘)
... return L
...
>> add_end()
[‘END‘]
>> add_end()
[‘END‘]
>> add_end()
[‘END‘]
>>

>>
>> def calc(number):
... sum=0
... for n in number:
... sum=sum+nn
... return sum
...
>> calc([1,2,3])
14
>> calc([1,2,3,4])
30
>> calc(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: calc() takes 1 positional argument but 3 were given
>>
>> def calc(
number):
... sum=0
... for n in number:
... sum=sum+n*n
... return sum
...
>> calc(1,2,3)
14
>> calc([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in calc
TypeError: can‘t multiply sequence by non-int of type ‘list‘
>> calc(1,2,3,4)
30
>>

>> calc(1,2)
5
>> calc()
0
>> nums = [1,2,3]
>> calc(nums[0],nums[1],nums[2])
14
>> calc(*nums)
14
>>

關鍵字參數

>>
>> def person(name,age,kw):
... print(‘name:‘,name,‘age:‘,age,‘other:‘,kw)
...
>>
>> person(‘Michael‘,30)
name: Michael age: 30 other: {}
>> person(‘Bob‘,35,city=‘Beijing‘)
name: Bob age: 35 other: {‘city‘: ‘Beijing‘}
>> person(‘Adam‘,45,gender=‘M‘,job=‘Engineer‘)
name: Adam age: 45 other: {‘gender‘: ‘M‘, ‘job‘: ‘Engineer‘}
>>
>> extra={‘city‘:‘Beijing‘,‘job‘:‘Engineer‘}
>> person(‘Jack‘,24,city=extra[‘city‘],job=extra[‘job‘])
name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}
>>
>> person(‘Jack‘,24,
extra)
name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}
>>
extra表示把extra這個dict的所有key-value用關鍵字參數傳入到函數的kw參數,kw將獲得一個dict,註意kw獲得的dict是extra的一份拷貝,對kw的改動不會影響到函數外的extra.

命名關鍵字參數

>> def person(name,age,**kw):
... if ‘city‘ in kw:
... pass
... if ‘job‘ in kw:
... pass
... print(‘name‘,name,‘age‘,age,‘other:‘,kw)
...
>> person(‘Jack‘,24,city=‘Beijing‘,addr=‘Chaoyang‘,zipcode=123456)
name Jack age 24 other: {‘city‘: ‘Beijing‘, ‘addr‘: ‘Chaoyang‘, ‘zipcode‘: 123456}
>>

>> def person(name,age,*,city,job):
... print(name,age,city,job)
...
>> person(‘Jack‘,24,city=‘Beijing‘,job=‘Engineer‘)
Jack 24 Beijing Engineer
>>

如果函數定義中已經有了一個可變參數,後面跟著的命名關鍵字參數就不再需要一個特殊分隔符*了:

>>
>> def person(name,age,args,city,job):
... print(name,age,args,city,job)
...
>> person(‘Jack‘,24,‘Beijing‘,‘Engineer‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: person() missing 2 required keyword-only arguments: ‘city‘ and ‘job‘
>> person(‘Jack‘,24,city=‘Beijing‘,‘Engineer‘)
File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument
>> person(‘Jack‘,24,city=‘Beijing‘,job=‘Engineer‘)
Jack 24 () Beijing Engineer
>>
>>
命名關鍵字參數可以有缺省值,從而簡化調用:
>>
>>
>> def person(name,age,
,city=‘Beijing‘,job):
... print(name,age,city,job)
...
由於命名關鍵字參數city具有默認值,調用時,可不傳入city參數:
>> person(‘Jack‘,24,job=‘Engineer‘)
Jack 24 Beijing Engineer
>>

參數組合

>> def f1(a,b,c=0,*args,*kw):
... print(‘a=‘,a,‘b=‘,b,‘c=‘,c,‘args=‘,args,‘kw=‘,kw)
...
>>
>> def f2(a,b,c=0,
,d,**kw):
... print(‘a=‘,a,‘b=‘,b,‘c=‘,c,‘d=‘,d,‘kw=‘,kw)
...
>>
>> f1(1,2)
a= 1 b= 2 c= 0 args= () kw= {}
>> f1(1,2,c=3)
a= 1 b= 2 c= 3 args= () kw= {}
>> f1(1,2,‘a‘,‘b‘)
a= 1 b= 2 c= a args= (‘b‘,) kw= {}
>> f1(1,2,3,‘a‘,‘b‘)
a= 1 b= 2 c= 3 args= (‘a‘, ‘b‘) kw= {}
>> f1(1,2,3,‘a‘,‘b‘,‘c‘)
a= 1 b= 2 c= 3 args= (‘a‘, ‘b‘, ‘c‘) kw= {}
>> f1(1,2,3,‘a‘,‘b‘,‘c‘,x=98)
a= 1 b= 2 c= 3 args= (‘a‘, ‘b‘, ‘c‘) kw= {‘x‘: 98}
>>
>> f2(1,2,d=23,ext=None)
a= 1 b= 2 c= 0 d= 23 kw= {‘ext‘: None}
>>

通過一個tuple和dict,也可以調用上述函數:

>> args=(1,2,3,4)
>>
>> kw={‘d‘:99,‘x‘:‘#‘}
>>
>> f1(*args,kw)
a= 1 b= 2 c= 3 args= (4,) kw= {‘d‘: 99, ‘x‘: ‘#‘}
>>
>>
>> f2(*args,*kw)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f2() takes from 2 to 3 positional arguments but 4 positional arguments (and 1 keyword-only argument) were given
>>
>> args=(1,2,3)
>>
>> kw={‘d‘:88,‘x‘:‘#‘}
>>
>> f2(
args,
kw)
a= 1 b= 2 c= 3 d= 88 kw= {‘x‘: ‘#‘}
>>

[root@mantisbt01 python]# cat ./15.py
#!/usr/bin/python

#-- coding:utf-8 --

def product(numbers):
product=1
if numbers==():
raise TypeError
else:
for n in numbers:
product=product
n

print(‘product =‘,product)

    return product

#test
print(‘product(5) =‘,product(5))
print(‘product(5,6) =‘,product(5,6))
print(‘product(5,6,7) =‘,product(5,6,7))
print(‘product(5,6,7,9) =‘,product(5,6,7,9))

if product(5) != 5:
print(‘test failed!‘)
elif product(5,6) != 30:
print(‘test failed!‘)
elif product(5,6,7) != 210:
print(‘test failed!‘)
elif product(5,6,7,9) != 1890:
print(‘test failed!‘)
else:
try:
product()
print(‘test failed!‘)
except TypeError:
print(‘test successful‘)
[root@mantisbt01 python]# ./15.py
product(5) = 5
product(5,6) = 30
product(5,6,7) = 210
product(5,6,7,9) = 1890
test successful
[root@mantisbt01 python]#

遞歸函數

>> def fact(n):
... if n==1:
... return 1
... return n*fact(n-1)
...
>> fact(1)
1
>> fact(5)
120
>> fact(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
>> fact(1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in fact
File "<stdin>", line 4, in fact
File "<stdin>", line 4, in fact
[Previous line repeated 994 more times]
File "<stdin>", line 2, in fact
RecursionError: maximum recursion depth exceeded in comparison
>>

[root@mantisbt01 python]# python
Python 3.6.4 (default, Mar 19 2018, 10:30:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>> def fact(n):
... return fact_iter(n,1)
...
>> def fact_iter(num,product):
... if num==1:
... return product
... return fact_iter(num-1,num*product)
...
>> fact_iter(5,1)
120
>> fact_iter(10,1)
3628800
>> fact_iter(1,1)
1
>> fact_iter(20,1)
2432902008176640000
>> fact_iter(1000,1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in fact_iter
File "<stdin>", line 4, in fact_iter
File "<stdin>", line 4, in fact_iter
[Previous line repeated 994 more times]
File "<stdin>", line 2, in fact_iter
RecursionError: maximum recursion depth exceeded in comparison
>>

>> fact(10)
3628800
>> def fact(n):
... s=1
... for i in range(1,n+1):
... s=si
... return s
...
>> fact(10)
3628800
>> fact(5)
120
>> from functools import reduce
>> def Fact(n):
... return reduce((lambda x,y:x
y),list(range(1,n+1)))
...
>> Fact(5)
120
>> Fact(10)
3628800
>>

漢諾塔的移動可以用遞歸函數非常簡單地實現。

請編寫move(n, a, b, c)函數,它接收參數n,表示3個柱子A、B、C中第1個柱子A的盤子數量,然後打印出把所有盤子從A借助B移動到C的方法,例如:
[root@mantisbt01 python]# cat ./17.py
#!/usr/bin/python

#-- coding:utf-8 --

def move(n,a,b,c):
if n==1:
step=1
print(a,‘-->‘,c)
return step
else:
s1=move(n-1,a,c,b)
s2=move(1,a,b,c)
s3=move(n-1,b,a,c)
step=s1+s2+s3
return step

s=move(3,‘A‘,‘B‘,‘C‘)
print(‘need %d steps‘%s)
[root@mantisbt01 python]# ./17.py
A --> C
A --> B
C --> B
A --> C
B --> A
B --> C
A --> C
need 7 steps
[root@mantisbt01 python]#

高級特性
比如構造一個1, 3, 5, 7, ..., 99的列表,可以通過循環實現:

L = []
n = 1
while n <= 99:
L.append(n)
n = n + 2
取list的前一半的元素,也可以通過循環實現。

但是在Python中,代碼不是越多越好,而是越少越好。代碼不是越復雜越好,而是越簡單越好。

基於這一思想,我們來介紹Python中非常有用的高級特性,1行代碼能實現的功能,決不寫5行代碼。請始終牢記,代碼越少,開發效率越高。
法1:

>> L=[]
>> n=1
>> while n<=99:
... L.append(n)
... n=n+2
...
>> L
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
>>

法2:

>> print(list(range(1,100,2)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

法3:

>> print([i for i in range(1,100,2)])
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
>>

1.切片
1.1 list

>> L=[‘Michael‘,‘Sarah‘,‘Tracy‘,‘Bob‘,‘Jack‘]
>> [L[0],L[1],L[2]]
[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
>> [L[-1],L[-2],L[-3]]
[‘Jack‘, ‘Bob‘, ‘Tracy‘]
>> r=[]
>> n=3
>> for i in range(n):
... r.append(L[i])
...
>> r
[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
>> L[0:3]
[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
>> L[0:4]
[‘Michael‘, ‘Sarah‘, ‘Tracy‘, ‘Bob‘]
>> L[1:3]
[‘Sarah‘, ‘Tracy‘]
>> L[:3]
[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
>> L[-2:]
[‘Bob‘, ‘Jack‘]
>> L[-2:-1]
[‘Bob‘]
>> L[-1]
‘Jack‘
>> L=list(range(100))
>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>> L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>> L[2:10:2]
[2, 4, 6, 8]
>> L[2:10:3]
[2, 5, 8]
>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
>> L[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>

1.2 tuple

>> (0,1,2,3,4,5)[:3]
(0, 1, 2)
>> ‘ABCDEFG‘[:3]
‘ABC‘
>> ‘ABCDEFG‘[::2]
‘ACEG‘
>>

利用切片操作,實現一個trim()函數,去除字符串首尾的空格,註意不要調用str的strip()方法:
[root@mantisbt01 python]# cat 18.py
#!/usr/bin/python

#-- coding:utf-8 --

#def trim(s):

if len(s) == 0:

return s

elif s[0] == ‘‘:

return (trim(s[1:]))

elif s[-1] == ‘ ‘:

return (trim(s[:-1]))

return s

def trim(s):
if s[:1] != ‘ ‘ and s[-1:] != ‘ ‘:
return s
elif s[:1] == ‘ ‘:
return trim(s[1:])
else:
return trim(s[:-1])

if trim(‘hello ‘) != ‘hello‘:
print(‘測試失敗!‘)
elif trim(‘ hello‘) != ‘hello‘:
print(‘測試失敗!‘)
elif trim(‘ hello ‘) != ‘hello‘:
print(‘測試失敗!‘)
elif trim(‘ hello world ‘) != ‘hello world‘:
print(‘測試失敗!‘)
elif trim(‘‘) != ‘‘:
print(‘測試失敗!‘)
elif trim(‘ ‘) != ‘‘:
print(‘測試失敗!‘)
else:
print(‘測試成功!‘)
[root@mantisbt01 python]# ./18.py
測試成功!

2.叠代

>> d={‘a‘:1,‘b‘:2,‘c‘:3}
>> for key in d:
... print(key)
...
a
b
c
>> for ch in ‘ABC‘:
... print(ch)
...
A
B
C
>>
>> from collections import Iterable
>> isinstance(‘abc‘,Iterable)
True
>> isinstance([1,2,3],Iterable)
True
>> isinstance(123,Iterable)
False
>>
>> for i,value in enumerate([‘A‘,‘B‘,‘C‘]):
... print(i,value)
...
0 A
1 B
2 C
>> for x,y in [(1,1),(2,4),(3,9)]:
... print(x,y)
...
1 1
2 4
3 9
>>

請使用叠代查找一個list中最小和最大值,並返回一個tuple:
使用冒泡排序法
[root@mantisbt01 python]# cat 19.py
#!/usr/bin/python

#-- coding:utf-8 --

def findMinandMax(L):
if (L==[]):
return (None,None)
else:
num=len(L)
for i in range(num):
for j in range(i):
if L[i]<L[j]:
L[i],L[j]=L[j],L[i]
return (L[0],L[-1])

if findMinandMax([]) != (None,None):
print(‘測試失敗!‘)
elif findMinandMax([7]) != (7,7):
print(‘測試失敗!‘)
elif findMinandMax([7,1]) != (1,7):
print(‘測試失敗!‘)
elif findMinandMax([7,1,3,9,5]) != (1,9):
print(‘測試失敗!‘)
else:
print(‘測試成功‘)
[root@mantisbt01 python]#
[root@mantisbt01 python]# ./19.py
測試成功

3.列表生成式

>>
>> list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> L=[]
>> for x in range(1,11):
... L.append(xx)
...
>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>> [x
x for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>> [x*x for x in range(1,11) if x%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(‘.‘)]
[‘18.py‘, ‘19.py‘, ‘1.py‘, ‘2.py‘, ‘3.py‘, ‘4.py‘, ‘5.py‘, ‘6.py‘, ‘7.py‘, ‘8.py‘, ‘9.py‘, ‘10.py‘, ‘11.py‘, ‘12.py‘, ‘13.py‘, ‘abstest.py‘, ‘pycache‘, ‘abstest2.py‘, ‘14.py‘, ‘15.py‘, ‘16.py‘, ‘17.py‘]

>> [d for d in os.listdir(‘/‘)]
[‘boot‘, ‘dev‘, ‘proc‘, ‘run‘, ‘sys‘, ‘etc‘, ‘root‘, ‘var‘, ‘tmp‘, ‘usr‘, ‘bin‘, ‘sbin‘, ‘lib‘, ‘lib64‘, ‘home‘, ‘media‘, ‘mnt‘, ‘opt‘, ‘srv‘, ‘.autorelabel‘]

>> [d for d in os.listdir(‘/home‘)]
[‘test2‘, ‘test3‘, ‘test4‘, ‘test1‘]

>> d={‘x‘:‘A‘,‘y‘:‘B‘,‘z‘:‘C‘}
>> for k,v in d.items():
... print(k,‘=‘,v)
...
x = A
y = B
z = C
>>
>> d={‘x‘:‘A‘,‘y‘:‘B‘,‘z‘:‘C‘}
>> [k+‘=‘+v for k,v in d.items()]
[‘x=A‘, ‘y=B‘, ‘z=C‘]
>> L=[‘Hello‘,‘World‘,‘IBM‘,‘Apple‘]
>> [s.lower() for s in L]
[‘hello‘, ‘world‘, ‘ibm‘, ‘apple‘]
>>
>>

>> L=[‘Hello‘,‘World‘,18,‘IBM‘,‘Apple‘]
>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: ‘int‘ object has no attribute ‘lower‘
>>

[root@mantisbt01 python]# cat 20.py
#!/usr/bin/python

#-- coding:utf-8 --

L1=[‘Hello‘,‘World‘,18,‘IBM‘,None]
L2=[s.lower() for s in L1 if isinstance(s,str)]

print(L2)
if L2 == [‘hello‘,‘world‘,‘ibm‘]:
print(‘測試通過!‘)
else:
print(‘測試失敗‘)
[root@mantisbt01 python]# ./20.py
[‘hello‘, ‘world‘, ‘ibm‘]
測試通過!
[root@mantisbt01 python]#

4.生成器

python3.6.4的學習