字符串:格式化python
>>> "{0} love {1}.{2}" .format("I","pyton","com")shell
'I love pyton.com'編程
>>> 服務器
>>> "{a} love {b}.{c}" .format(a='I',b='python',c='com')閉包
'I love python.com'app
>>> "{0} love {b}.{c}" .format('I',b='python',c='com')ide
'I love python.com'函數
>>> ui
>>> "{a} love {b}.{0}" .format(a='I',b='python','com')spa
SyntaxError: positional argument follows keyword argument
>>>
>>> print('\ta')
a
>>> print ('\\')
\
>>> "`0`" .format("不打印")
'{0}'
>>> '{0:.1f}{1}'.format(27.658,'GB')
'27.7GB'
>>>
>>> '%c' % 97
'a'
>>> '%c %c %c' % (97,98,99)
'a b c'
>>> '%s' % 'I love Python'
'I love Python'
>>> '%d + %d = %d' %(4,5,4+5)
'4 + 5 = 9'
>>> '%o' % 10
'12'
>>> '%x' % 10
'a'
>>> '%X' % 10
'A'
>>> '%f' % 27.658
'27.658000'
>>> '%e' % 27.658
'2.765800e+01'
>>> '%E' % 27.658
'2.765800E+01'
>>> '%G' % 27.658
'27.658'
>>>
>>> '%f' % 27.658
'27.658000'
>>> '%e' % 27.658
'2.765800e+01'
>>> '%E' % 27.658
'2.765800E+01'
>>> '%G' % 27.658
'27.658'
>>> '%5.1f' % 27.658
' 27.7'
>>> '%.2e' % 27.658
'2.77e+01'
>>> '%10d' % 5
' 5'
>>> '%-10d' % 5
'5 '
>>> '%+10d' % 5
' +5'
>>>
>>> '%#o' % 10
'0o12'
>>> '%#X' % 108
'0X6C'
>>> '%#d' % 10
'10'
>>> '%010d' %5
'0000000005'
>>> '%-010d' %5
'5 '
>>>
序列!序列!
列表、元組和字符串的共同點
均可以經過索引獲得每個元素
默認索引值老是從0開始
能夠經過分片的方法獲得一個範圍內的元素的集合
有不少共同的操做符(重複操做符、拼接操做符、成員關係操做符)
>>> help(list)
Help on class list in module builtins:
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.n
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(...)
| L.__reversed__() -- return a reverse iterator over the list
|
| __rmul__(self, value, /)
| Return self*value.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| L.__sizeof__() -- size of L in memory, in bytes
|
| append(...)
| L.append(object) -> None -- append object to end
|
| clear(...)
| L.clear() -> None -- remove all items from L
|
| copy(...)
| L.copy() -> list -- a shallow copy of L
|
| count(...)
| L.count(value) -> integer -- return number of occurrences of value
|
| extend(...)
| L.extend(iterable) -> None -- extend list by appending elements from the iterable
|
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
|
| insert(...)
| L.insert(index, object) -- insert object before index
|
| pop(...)
| L.pop([index]) -> item -- remove and return item at index (default last).
| Raises IndexError if list is empty or index is out of range.
|
| remove(...)
| L.remove(value) -> None -- remove first occurrence of value.
| Raises ValueError if the value is not present.
|
| reverse(...)
| L.reverse() -- reverse *IN PLACE*
|
| sort(...)
| L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
>>>
迭代是重複反饋過程活動,其目的一般是爲了接近達到所需的目標或結果。
>>> a = list()
>>> a
[]
>>> b = 'I love Pyton'
>>> b = list(b)
>>> b
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'P', 'y', 't', 'o', 'n']
>>>
>>> c = (1,1,2,3,5,8,13,21,34)
>>> c = list(c)
>>> c
[1, 1, 2, 3, 5, 8, 13, 21, 34]
>>>
Tuple([iterable])把一個可迭代對象轉換爲元組
>>> help(tuple)
Help on class tuple in module builtins:
class tuple(object)
| tuple() -> empty tuple
| tuple(iterable) -> tuple initialized from iterable's items
|
| If the argument is a tuple, the return value is the same object.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.n
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return self*value.
|
| count(...)
| T.count(value) -> integer -- return number of occurrences of value
|
| index(...)
| T.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
>>>
Str(obj)把obj對象轉換爲字符串
>>> len(a)
0
>>> len(b)
12
>>> b
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'P', 'y', 't', 'o', 'n']
max()返回序列或者參數集合中的最大值
>>> max(1,2,3,4,5)
5
>>> max(b)
'y'
>>> numbers = [1,18,13,0,-98,34,67,89,32]
>>> max(numbers)
89
>>>
min()返回序列或者參數集合中的最小值
>>> min(numbers)
-98
>>> chars = '1234567890'
>>> min(chars)
'0'
>>> tuple1 = (1,2,3,4,5,6,7,8,9,0)
>>> min(tuple1)
0
>>>
sum(iterable[,start=0])返回序列iterable和可選參數start的總和
>>> tuple2 = (3,1,2,3,3,4)
>>> sum(tuple2)
16
>>> sum(tuple2,4)
20
>>>
>>> chars
'1234567890'
>>> sum(chars)
Traceback (most recent call last):
File "<pyshell#256>", line 1, in <module>
sum(chars)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
>>> sorted(numbers)
[-98, 0, 1, 13, 18, 32, 34, 67, 89]
>>> reversed(numbers)
<list_reverseiterator object at 0x0000000002DDCFD0>
>>> list(reversed(numbers))
[32, 89, 67, 34, -98, 0, 13, 18, 1]
>>> enumerate(numbers)
<enumerate object at 0x0000000002E0F750>
>>> list(enumerate(numbers))
[(0, 1), (1, 18), (2, 13), (3, 0), (4, -98), (5, 34), (6, 67), (7, 89), (8, 32)]
>>> a = [1,2,3,4,5,6,7,8]
>>> b = [4,5,6,7,8]
>>> zip (a,b)
<zip object at 0x0000000002E09648>
>>> list(zip(a,b))
[(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]
>>>
函數:Python的樂高積木
函數
對象
模塊
>>> def MySecondFunction(name):
print(name + '我愛你')
>>> MySecondFunction('jm')
jm我愛你
>>> MySecondFunction('j')
j我愛你
>>> def add(num1 , num2):
result = num1 + num2
print(result)
>>> def add(num1 , num2):
result = num1 + num2
print(result)
>>> add(1 , 2)
3
>>> def add(num1 , num2):
return (num1 + num2)
>>> print (add(5 , 6))
11
>>> print (11)
11
>>>
形參和實參
>>> def MyFirstFunction(name):
'函數定義過程當中的name是叫形參'
#由於Ta只是一個形式,表示佔據一個參數位置
print('傳遞進來的' + name + '叫作實參,由於Ta是具體的參數值!')
>>> MyFirstFunction('jm')
傳遞進來的jm叫作實參,由於Ta是具體的參數值!
形式參數(parameter) 實際參數(argument)
函數文檔
>>> def MyFirstFunction(name):
'函數定義過程當中的name是叫形參'
#由於Ta只是一個形式,表示佔據一個參數位置
print('傳遞進來的' + name + '叫作實參,由於Ta是具體的參數值!')
>>> MyFirstFunction('jm')
傳遞進來的jm叫作實參,由於Ta是具體的參數值!
>>> MyFirstFunction.__doc__
'函數定義過程當中的name是叫形參'
>>>
>>> help(MyFirstFunction)
Help on function MyFirstFunction in module __main__:
MyFirstFunction(name)
函數定義過程當中的name是叫形參
>>> print .__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>>
關鍵字參數
>>> def SaySome(name , words):
print(name + '->' + words)
>>> SaySome('jm','讓編程改變世界!')
jm->讓編程改變世界!
>>> SaySome('讓編程改變世界!','jm')
讓編程改變世界!->jm
>>> SaySome(words='讓編程改變世界!',name='jm')
jm->讓編程改變世界!
>>>
默認參數
>>> def SaySome(name='jm',words='讓編程改變世界!'):
print(name + '->' + words)
>>> SaySome()
jm->讓編程改變世界!
>>> SaySome('j')
j->讓編程改變世界!
>>> SaySome('j','m')
j->m
>>>
收集參數
>>> def test(*params):
print('參數的長度是:',len(params));
print('第二參數是:',params[1]);
>>> test(1,'jm',3,14,5,6,7,8,9)
參數的長度是: 9
第二參數是: jm
>>>
>>> def test(*params,exp):
print('參數的長度是:',len(params),exp);
print('第二參數是:',params[1]);
>>> test(1,'jm',3,14,5,6,7,8,9)
Traceback (most recent call last):
File "<pyshell#321>", line 1, in <module>
test(1,'jm',3,14,5,6,7,8,9)
TypeError: test() missing 1 required keyword-only argument: 'exp'
>>> test(1,'jm',3,14,5,6,7,8,exp = 9)
參數的長度是: 8 9
第二參數是: jm
>>>
函數與過程
>> def hello():
print("Hello python")
>>> temp = hello()
Hello python
>>> temp
>>>
>>> print(temp)
None
>>>
>>> type(temp)
<class 'NoneType'>
>>>
再談談返回值
>>> def back():
return [1,'a',3.14]
>>> back()
[1, 'a', 3.14]
>>> def back():
return 1,'a',3.14
>>> back()
(1, 'a', 3.14)
>>>
個人地盤聽個人
def discounts(price, rate):
final_price = price * rate
old_price = 88 #這裏試圖修改全局變量
print('修改後old_price的值是:', old_price)
return final_price
old_price = float(input('請輸入原價:'))
rate = float(input('請輸入折扣率:'))
new_price = discounts(old_price, rate)
print('修改後old_price的值是:', old_price)
print('打折後價格是:', new_price)
函數:內嵌函數和閉包
>>> count = 5
>>> def MyFun():
count = 10
print(10)
>>> MyFun()
10
>>> print (count)
5
>>>
>>> def MyFun():
global count
count = 10
print (10)
>>> MyFun()
10
>>> print(count)
10
>>>
內嵌函數
>>> def fun1():
print('fun1()正在被調用...')
def fun2():
print('fun2()正在被調用...')
fun2()
>>> fun1()
fun1()正在被調用...
fun2()正在被調用...
>>>
閉包
>>> def FunX(x):
def FunY(y):
return x * y
return FunY
>>> i=FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x0000000002E406A8>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40
>>>
>>> FunY(5)
Traceback (most recent call last):
File "<pyshell#374>", line 1, in <module>
FunY(5)
NameError: name 'FunY' is not defined
>>>
>>> def Fun1():
x=5
def Fun2():
x *= x
return x
return Fun2()
>>> Fun1()
Traceback (most recent call last):
File "<pyshell#386>", line 1, in <module>
Fun1()
File "<pyshell#385>", line 6, in Fun1
return Fun2()
File "<pyshell#385>", line 4, in Fun2
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
>>>
>>> def Fun1():
x = [5]
def Fun2():
x[0] *= x[0]
return x[0]
return Fun2()
>>> Fun1()
25
>>>
>>> def Fun1():
x = 5
def Fun2():
nonlocal x
x *= x
return x
return Fun2()
>>> Fun1()
25
>>>
函數:lambda表達式
>>> def ds(x):
return 2* x + 1
>>> ds(5)
11
>>> lambda x : 2 * x + 1
<function <lambda> at 0x0000000002E40AE8>
>>> g = lambda x : 2 * x + 1
>>> g(5)
11
>>> def add(x,y):
return x + y
>>> add(3,4)
7
>>> lambda x , y : x + y
<function <lambda> at 0x0000000002E1DF28>
>>> g = lambda x , y : x + y
>>> g(3 , 4)
7
>>>
l Python寫一些執行腳本時,使用lambda就能夠省下定義函數過程,好比說咱們只是須要寫個簡單的腳原本管理服務器時間,咱們就不須要專門定義一個函數而後再寫調用,使用lambda就可使得代碼更加精簡。
l 對於一些比較抽象而且整個程序執行下來只須要調用一兩次的函數,有時候給函數起個名字也是比較頭疼的問題,使用lambda就不須要考慮命名的問題了。
l 簡化代碼的可讀性,因爲普通的屌絲函數閱讀常常要跳到開頭def定義部分,使用lambda函數能夠省去這樣的步驟。
兩個牛逼的BIF
>>> help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
>>> filter(None,[1,0,False,True])
<filter object at 0x0000000002E41EB8>
>>> list(filter(None,[1,0,False,True]))
[1, True]
>>> def odd(x):
return x % 2
>>> temp = range(10)
>>> show = filter(odd,temp)
>>> list(show)
[1, 3, 5, 7, 9]
>>> list(filter(lambda x : x % 2, range(10)))
[1, 3, 5, 7, 9]
>>>
>>> list(map(lambda x : x * 2, range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>