從下圖中可以知道python3中有如下這些內(nèi)置函數(shù)
下面我們一一了解下每個函數(shù)的用法:
abs()
abs()
函數(shù)是取絕對值的函數(shù),在C語言只中有也有一個abs()
函數(shù)但是在C語言中abs()
函數(shù)的參數(shù)要求是整數(shù)姻灶,在C語言中如果要對一個浮點數(shù)取絕對值則應該用fabs()
函數(shù)红碑,但是在python中則不一樣,abs()
函數(shù)是對參數(shù)沒有要求的 绰上,不管是整數(shù)函數(shù)浮點數(shù)都可以旨怠,并且在使用abs()
函數(shù)是你傳遞的參數(shù)是什么類型的,返回的函數(shù)的類型也是相對應的類型
>>> abs(-1)
1
>>> abs(-2.0)
2.0
>>> type(abs(-2.4))
<class 'float'>
>>> type(abs(-2))
<class 'int'>
all() any()
all()
和 any()
功能類似都是判斷一個可迭代對象是否為真
這兩個函數(shù)的返回值都是boolean
值
首先我們應該了解在python3中哪些數(shù)據(jù)會被判斷為False
a = 0 # 整數(shù)0,False
print(bool(a))
s = "" # 空字符串蜈块,F(xiàn)alse
print(bool(s))
lst = [] # 空列表鉴腻,F(xiàn)alse
print(bool(lst))
dic = {} # 空字典,F(xiàn)alse
print(bool(dic))
a = None # None表示空百揭,真空爽哎,F(xiàn)alse
print(bool(a))
除了以上數(shù)據(jù),則都會被判斷為True
all() any()的英文文檔描述
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
# 如果可迭代對象中的所有元素都是Ture則返回True器一,也可以理解為把可迭代對象中的所有元素做與運算
# 函數(shù)原型為
def all(iterable):
for element in iterable:
if not element:
return False
return True
例子
>>> all(['a',(2,4),1,True]) #list都為真
True
>>> all(['a',(),1,True]) #list元素中有空tuple
False
>>> all(['a',(2,4),0,True]) #有0
False
>>> all(['a',(2,4),3,False]) #有False
False
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
# 如果可迭代對象中存在元素是Ture則返回True课锌,也可以理解為把可迭代對象中的所有元素做或運算
#函數(shù)原型為
def any(iterable):
for element in iterable:
if element:
return True
return False
例子
>>> any(['a',(2,4),3,True])
True
>>> any(['a',(2,4),3,False])
True
>>> any(['a',(),3,False])
True
>>> any(['',(),0,False])
False
>>> any(('a',(),3,False))
True
>>> any(('',(),0,False))
False
ascii(object)
返回一個可打印的對象字符串方式表示,如果是非ascii字符就會輸出\x祈秕,\u或\U等字符來表示渺贤。與python2版本里的repr()是等效的函數(shù)。
>>> ascii(1)
'1'
>>> ascii('$')
"'$'"
>>> ascii(999999)
'999999'
>>> ascii('中國')
"'\\u4e2d\\u56fd'"
bin(), oct(), hex()
bin()
把十進制轉化為二進制
>>> bin(7)
'0b111'
>>> bin(-7)
'-0b111'
>>> bin(1.1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
oct()
把十進制轉化為8進制
>>> oct(10)
'0o12'
>>> oct(-10)
'-0o12'
>>> oct(-10.4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
hex
把十進制數(shù)轉化為16進制
>>> hex(17)
'0x11'
>>> hex(-17)
'-0x11'
>>> hex(17.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
注意參數(shù)只能是整數(shù)
bool()
測試一個對象是True還是False.
>>> bool([])
False
>>> bool([''])
True
>>> bool(())
False
>>> bool(0)
False
>>> bool(4)
True
>>> bool(1.1)
True
>>> bool({})
False
>>> bool(['hello', 'world'])
True
bytes()
將一個字符串轉換成字節(jié)類型
我們都知道在計算機的底層都是保存的二進制信息不管是數(shù)字還是文字都是轉化為相對應的二進制格式保存在硬盤之中
我們都知道比如一個十進制的數(shù)字15
轉化為二進制位1111
请毛,直接把1111
保存在計算機中志鞍,但是我們的文字文本信息是怎么轉化為這種二進制信息的呢?
這里就要涉及到計算機中的編碼技術获印,我們最熟知的編碼無非就是ASCII
編碼了述雾,但是在ASCII
編碼中并沒有中文字符的編碼規(guī)范,然后為了在計算機中表示中文兼丰,相應的兼容中文的編碼規(guī)范就出臺了玻孟,比如有GB2312
, GBK
, UTF-8
等等。(最常用的還是UTF-8
)
UTF-8的具體規(guī)范
GBK規(guī)范
這里我們只需要了解鳍征,一個中文漢子用GBK
編碼需要2字節(jié)黍翎,用UTF-8
需要三個字節(jié)
例子
>>> bytes('中國', encoding='utf-8')
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> bytes('中國', encoding='UTF-8') # 編碼格式不區(qū)分大寫小寫
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> bytes('中國', encoding='gbk')
b'\xd6\xd0\xb9\xfa'
bytearray()
bytearray()
函數(shù)的官方文檔描述是:
def __init__(self, source=None, encoding=None, errors='strict'): # known special case of bytearray.__init__
"""
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array
Construct a mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
# (copied from class doc)
"""
pass
- 當三個參數(shù)都不傳時
>>> b = bytearray()
>>> b
bytearray(b'')
>>> len(b)
0
- 當source參數(shù)為字符串時,encoding參數(shù)也必須提供艳丛,函數(shù)將字符串使用str.encode方法轉換成字節(jié)數(shù)組
>>> bytearray('中文')
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
bytearray('中文')
TypeError: string argument without an encoding
>>> bytearray('中文','utf-8')
bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
- 當source參數(shù)為整數(shù)時匣掸,返回這個整數(shù)所指定長度的空字節(jié)數(shù)組
>>> bytearray(2)
bytearray(b'\x00\x00')
>>> bytearray(-2)
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
bytearray(-2)
ValueError: negative count
傳遞的整數(shù)參數(shù)需大于0,使用來做數(shù)組長度的
- 當source參數(shù)是一個可迭代對象氮双,那么這個迭代對象的元素都必須符合0 <= x < 256碰酝,以便可以初始化到數(shù)組里
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray([256,2,3]) #不在0-255范圍內(nèi)報錯
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
bytearray([256,2,3])
ValueError: byte must be in range(0, 256)
callable()
callable()
函數(shù)用于檢查一個對象是否是可調用的。如果返回True
戴差,object
仍然可能調用失斔桶帧;但如果返回False
,調用對象ojbect
絕對不會成功袭厂。
對于函數(shù), 方法, lambda 函式, 類, 以及實現(xiàn)了 __call__
方法的類實例, 它都返回 True墨吓。
例子
>>>callable(0)
False
>>> callable("runoob")
False
>>> def add(a, b):
... return a + b
...
>>> callable(add) # 函數(shù)返回 True
True
>>> class A: # 類
... def method(self):
... return 0
...
>>> callable(A) # 類返回 True
True
>>> a = A()
>>> callable(a) # 沒有實現(xiàn) __call__, 返回 False
False
>>> class B:
... def __call__(self):
... return 0
...
>>> callable(B)
True
>>> b = B()
>>> callable(b) # 實現(xiàn) __call__, 返回 True
True
chr() ord()
chr()
函數(shù)是把Unicode
字符轉化為對應的十進制數(shù)字
ord()
函數(shù)則相反這是把數(shù)字轉為對應的Unicode
字符,不一定是十進制其他進制也可以
例子
>>> ord('你')
20320
>>>ord('a')
97
>>> ord('b')
98
>>> ord('c')
99
>>> ord('ab')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
>>> chr(97)
'a'
>>> chr(65)
'A'
>>> chr(20320)
'你'
>>> chr(3874298)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(0x110000)
chr 的參數(shù)應該比0x110000小
compile() exec() eval()
compile(str, file, type)
我們知道我們寫出來的源代碼都是需要進行編譯或者翻譯成機器碼才能被我們的計算機執(zhí)行纹磺,compile
語句的目的是提供一次性的字節(jié)碼編譯帖烘,就不用在以后的每次調用中重新進行編譯了。
還需要注意的是橄杨,這里的compile和正則表達式中使用的compile并不相同秘症,盡管用途一樣。
例子
>>> c = compile(str,'<string>','exec')
>>> c
<code object <module> at 0x100dbfed0, file "<string>", line 1>
>>> exec(c)
0
1
2
>>> str = 'print("hello")'
>>> c = compile(str,'<string>','eval')
>>> eval(c)
hello
>>> single_code = compile( 'print("pythoner.com")', '<string>', 'single' )
>>> exec(single_code)
pythoner.com
>>> eval(single_code)
pythoner.com
compile語句是從type類型(總共有三種類型包括'
eval
'讥珍,'exec
'历极,'single
': 著山中類型分別的用法是,single
便是我們編譯的代碼只有一行衷佃,eval
表示會把字符串編譯成一個表達式,exec
表示會把字符串編譯成一個和python一模一樣的東西蹄葱,比如就可以有for 循環(huán) )中將字符串語句創(chuàng)建成代碼對象氏义。
eval()
eval()還可以單獨直接執(zhí)行表達式
例子
>>> eval('3*2')
6
>>> eval('print("hello world!")')
hello world!
exec()
exec()可以把符合python規(guī)范的字符串當成python語句進行執(zhí)行,如果直接用這種方式執(zhí)行每次都得編譯一次
例子
>>> exec('for i in range(3): print(i)')
0
1
2
>>> exec('print(4)')
4
>>> exec('9*9')
eval執(zhí)行表達式后是具有返回值的图云,但是exec是沒有返回值的
complex()
函數(shù)為:complex([real[, imag]])
complex()函數(shù)是處理復數(shù)的函數(shù)具體有如下用法:
例子
- 當兩個參數(shù)都不提供時惯悠,返回復數(shù)
0j
。(j
是python中的復數(shù)標志竣况,和我們數(shù)學課上學過的i
是一樣的)
>>> complex()
0j
- 當?shù)谝粋€參數(shù)為字符串時克婶,調用時不能提供第二個參數(shù)。此時字符串參數(shù)丹泉,需是一個能表示復數(shù)的字符串情萤,而且加號或者減號左右不能出現(xiàn)空格。
>>> complex('2.3+9j')
(2.3+9j)
>>> complex('3+3j', 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: complex() can't take second arg if first is a string
>>> complex('2 + 3j')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string
- 當?shù)谝粋€參數(shù)為int或者float時摹恨,第二個參數(shù)可為空筋岛,表示虛部為0;如果提供第二個參數(shù)晒哄,第二個參數(shù)也需為int或者float睁宰。
>>> complex(2)
(2+0j)
>>> complex(3.1)
(3.1+0j)
>>> complex(3,4.2)
(3+4.2j)
dict()
dict() 函數(shù)用于創(chuàng)建一個字典。返回一個字典
>>>dict() # 創(chuàng)建空字典
{}
>>> dict(a='a', b='b', t='t') # 傳入關鍵字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函數(shù)方式來構造字典
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代對象方式來構造字典
{'three': 3, 'two': 2, 'one': 1}
dir()
函數(shù)不帶參數(shù)時寝凌,返回當前范圍內(nèi)的變量柒傻、方法和定義的類型列表;帶參數(shù)時较木,返回參數(shù)的屬性红符、方法列表。如果參數(shù)包含方法dir(),該方法將被調用违孝。如果參數(shù)不包含dir()刹前,該方法將最大限度地收集參數(shù)信息。
例子
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'i']
>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
divmod()
函數(shù)把除數(shù)和余數(shù)運算結果結合起來雌桑,返回一個包含商和余數(shù)的元組(a // b, a % b)喇喉。
例子
>>>divmod(7, 2)
(3, 1)
>>> divmod(8, 2)
(4, 0)
>>> divmod(1+2j,1+0.5j) #復數(shù)也可以進行出發(fā)運算
((1+0j), 1.5j)
>>> div(12.3,7) # 只能進行整數(shù)的出發(fā)運算
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'div' is not defined
enumerate()
函數(shù)用于將一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串)組合為一個索引序列校坑,同時列出數(shù)據(jù)和數(shù)據(jù)下標拣技,一般用在 for 循環(huán)當中。
例子
>>> enumerate([3,7,8])
<enumerate object at 0x10fc05948>
>>> list(enumerate([3,7,8]))
[(0, 3), (1, 7), (2, 8)]
>>> list(enumerate([3,7,8], start=4))
[(4, 3), (5, 7), (6, 8)]
使用for循遍歷一個list
>>> i=0
>>> seq = ['pig', 'panda', 'duck']
>>> for ele in seq:
... print(i, ele)
... i+=1
...
0 pig
1 panda
2 duck
結合enumerate使用for循環(huán)遍歷
>>> seq = ['pig', 'panda', 'duck']
>>> for n, ele in enumerate(seq):
... print(n, ele)
...
0 pig
1 panda
2 duck
id()
函數(shù)用于獲取對象的內(nèi)存地址耍目。
在python中既可以進行面對對象的編程膏斤,也可以面對過程的編程,但是總的來說一切皆對象
,這句話不不容易理解的邪驮,需要我們對編程有深層次的學習后才能完全的體會到這句話的含義莫辨,但是我們不用著急學習的過程總是循序漸進的。
>>> id(seq)
4559234440
>>> id([])
4559234568
>>> a = 1
>>> id(a)
4555139008
isinstance()
判斷一個一個對象是否是一個類的實例毅访,或者判斷一個對象是否是一個類的子類的實例
這了的概念是和類有關的沮榜,如果看不懂則先去學習一個python面對對象編程
例子
>>> a = 1
>>> id(a)
4555139008
>>> isinstance(a, int)
True
>>> s = 'string object'
>>> isinstance(s, str)
True
>>> isinstance(s, dict)
False
filter()
filter() 函數(shù)用于過濾序列(對一個可迭代對象進行篩選,去掉不需要的元素)喻粹,過濾掉不符合條件的元素蟆融,返回由符合條件元素組成的新列表。
該接收兩個參數(shù)守呜,第一個為函數(shù)型酥,第二個為序列,序列的每個元素作為參數(shù)傳遞給函數(shù)進行判查乒,然后返回 True 或 False弥喉,最后將返回 True 的元素放到新列表中。
例子
需求去除序列[1,2,3,4,5,6]中的奇數(shù)
普通方法
>>> lis = [1,2,3,4,5,6]
>>> ret = []
>>> def get_even_number_list(lis):
... for i in lis:
... if i % 2 == 0:
... ret.append(i)
...
>>> get_even_number_list(lis)
>>> ret
[2, 4, 6]
使用filter
方法
>>> isinstance(s, dict)
False
>>> lis = [1,2,3,4,5,6]
>>> def is_even_number(x):
... if x%2 == 0:
... return True
... else:
... return False
...
>>> list(filter(is_even_number, lis))
[2, 4, 6]
>>> list(filter(lambda x:x%2==0, lis)) #如果使用lambda表達式會更加簡單
[2, 4, 6]
從上面兩個的做法中我們就可以比較兩個方法侣颂,使用filter方法還是很方便的
map()
map()
函數(shù)的功能是接受兩個參數(shù)档桃,前一個是一個方法,后一個是一個可迭代對象憔晒,map()
是把每一個可迭代對象中的元素去除做一定操作然后更新這個元素
例子
>>> lis = [101, 102, 103, 104, 105, 106]
>>> map(lambda x:x-50, lis)
<map object at 0x1064be588>
>>> list(map(lambda x:x-50, lis))
[51, 52, 53, 54, 55, 56]
在python2.7以后
map
filter
函數(shù)的返回值是返回一個可迭代對象
globals() locals()
globals()
是獲取有的全局變量
locals()
是獲取有的局部變量
例子
>>> g = 1
>>> def f():
... a = 2
... print(globals())
... print(locals())
...
>>> f()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'g': 1, 'f': <function f at 0x1018ebe18>} #存在的全局變量
{'a': 2} #局部變量
hash()
hash()
哈希本來是密碼學中的一種消息摘要算法藻肄,用途很廣泛。如果像深入的了解什么是哈希函數(shù)拒担,可以去百度上學習學習
例子
>>> s = 'hello'
>>> hash(s)
779082262045361556
>>> type(hash(s))
<class 'int'>
int()
int()
函數(shù)用于將一個字符串或數(shù)字轉換為整型嘹屯。
int()
函數(shù)有兩個參數(shù)分別是int(x, base=10)
- x -- 字符串或數(shù)字。
- base -- 進制數(shù)从撼,默認十進制州弟。
例子
>>>int() # 不傳入?yún)?shù)時钧栖,得到結果0
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16) # 如果是帶參數(shù)base的話,12要以字符串的形式進行輸入婆翔,12 為 16進制
18
>>> int('0xa',16)
10
>>> int('10',8)
8
input()
大家都知道python有2.X和3.X版本的但是現(xiàn)在很多都是使用python3了拯杠,這只只討論3版本。
在python3.X中raw_input( )和input( )進行了整合啃奴,在3.X版本中去除了raw_input( )潭陪,僅保留了input( )函數(shù),其接收任意任性輸入最蕾,將所有輸入默認為字符串處理依溯,并返回字符串類型。
如果像了解下python2.X的input函數(shù)可以去菜鳥教程上學習下這里不做過多的講解了
在python3中的input()
函數(shù)中所有的輸入都就被當成是字符串
例子
>>> a = input('input:')
input:string
>>> type(a)
<class 'str'>
>>> i = int(input('input int number:')) # 這樣可以直接輸入一個整型
input int number:13
>>> type(i)
<class 'int'>
>>> i = float(input('輸入一個浮點數(shù):')) #輸入一個浮點數(shù)
輸入一個浮點數(shù):1.4
>>> type(i)
<class 'float'>
len()
這是一個使用非常頻繁的函數(shù)瘟则,并且是一個很強大的函數(shù)
返回對象(字符黎炉、列表、元組等)長度或項目個數(shù)醋拧。
例子
>>> string = 'testing'
>>> len(string)
7
>>> li = [1,2,3]
>>> len(li)
3
>>> dic = {'1':3,'3':5}
>>> len(dic)
2
>>> tu = (12,45,)
>>> len(tu)
2
這里提醒下python2中的len()
函數(shù)在計算中文字符串的長度的時候是以字符串占用的字節(jié)數(shù)來計算的慷嗜,下面請看例子:
Python 2.7.15 (default, May 1 2018, 16:44:08)
[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bytes('你是')
'\xe4\xbd\xa0\xe6\x98\xaf'
>>> len('你是')
6
但是在python3中,len()
函數(shù)還是以字符個數(shù)來計算長度
list()
把一個元組轉化為列表趁仙,或者一個可迭代的對象轉化為列表
例子
>>> str="Hello World"
>>> list2=list(str)
>>> list2
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> aTuple = (123, 'Google', 'Runoob', 'Taobao')
>>> list1 = list(aTuple)
>>> print ("列表元素 : ", list1)
列表元素 : [123, 'Google', 'Runoob', 'Taobao']
max() min()
max()
min()
函數(shù)分別是區(qū)最大值和最小值
具體的可以看輸入的例子學習下面的用法
>>> max(80, 100, 1000)
1000
>>> max((1,2,3,4))
4
>>> min((1,2,3,4))
1
>>> s = '12345'
>>> print(max(s))
5
>>> print(max((),default=1))
1
>>> print(max(())) #傳入可迭代對象為空時洪添,必須指定參數(shù)default,用來返回默認值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
>>> s = [
... {'name': 'sumcet', 'age': 18},
... {'name': 'bbu', 'age': 11}
... ]
>>> max(s, key=lambda x: x['age'])
{'name': 'sumcet', 'age': 18}
>>> prices = {'HPQ': 37.2, 'FB': 10.75, 'AAPL': 612.78, 'IBM': 205.55, 'ACME': 45.23}
>>> max(prices, key=lambda k: prices[k])
'AAPL'
min 和 max 的用法都是一樣的只是得到的結果是一個是最大一個是最小
pwd()
計算一個次方
例子
>>> 2**4
16
>>> pow(2, 4)
16
reversed()
reversed()
方法是取一有序序列的反序雀费,可以是 tuple, string, list 或 range。
例子
>>> l = [1,2,3,4]
>>> l.reverse() # str對象中的reverse方法頁具有反轉的功能
>>> l
[4, 3, 2, 1]
>>> reversed(l) # reversed() 的返回值是一個對象痊焊,如果可以我們可以把它轉為list或者是tuple
<list_reverseiterator object at 0x10aa0a898>
>>> l
[4, 3, 2, 1]
>>> l
[4, 3, 2, 1]
>>> list(reversed(l))
[1, 2, 3, 4]
>>> tuple(reversed(l))
(1, 2, 3, 4)
>>> list(reversed('AbcdefG'))
['G', 'f', 'e', 'd', 'c', 'b', 'A']
round()
round()
函數(shù)是取浮點數(shù)也就是小數(shù)的保留位數(shù)
round 有兩個參數(shù)盏袄,第一個是你要進行保留的小數(shù),第二個是你像保留的位數(shù)薄啥,如果不傳值默認為0辕羽,也就是默認保留到個位。
例子
>>> round(70.23456)
70
>>> round(56.659,1)
56.7
>>> round(80.264, 2)
80.26
>>> round(-100.000056, 3)
-100.0
set()
函數(shù)創(chuàng)建一個無序不重復元素集垄惧,可進行關系測試刁愿,刪除重復數(shù)據(jù),還可以計算交集到逊、差集铣口、并集等。
例子
>>>x = set('runoob')
>>> y = set('google')
>>> x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l'])) # 重復的被刪除
>>> x & y # 交集
set(['o'])
>>> x | y # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y # 差集
set(['r', 'b', 'u', 'n'])
range()
range(start, stop[, step])
特別常用
range函數(shù)返回的是一個可迭代對象(類型是對象)觉壶,而不是列表類型脑题, 所以打印的時候不會打印列表。
- 計數(shù)從 start 開始铜靶。默認是從 0 開始叔遂。例如range(5)等價于range(0, 5);
- 計數(shù)到 stop 結束,但不包括 stop已艰。例如:range(0痊末, 5) 是[0, 1, 2, 3, 4]沒有5。
- 步長哩掺,默認為1凿叠。例如:range(0, 5) 等價于 range(0, 5, 1)
例子
>>> range(10)
range(0, 10)
>>> range(2,10)
range(2, 10)
>>> range(1,4,2)
range(1, 4, 2)
>>> for i in range(1,4,2):
... print(i)
...
1
3
>>> for i in range(0,3,-1):
... print(i)
...
>>> for i in range(3,0,-1):
... print(i)
...
3
2
1
zip()
函數(shù)用于將可迭代的對象作為參數(shù)疮丛,將對象中對應的元素打包成一個個元組幔嫂,然后返回由這些元組組成的對象,這樣做的好處是節(jié)約了不少的內(nèi)存誊薄。
我們可以使用 list() 轉換來輸出列表履恩。
如果各個迭代器的元素個數(shù)不一致,則返回列表長度與最短的對象相同呢蔫,利用 *
號操作符切心,可以將元組解壓為列表。
例子
壓縮
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> v = [7,8,9]
>>> zip(a,b,v)
<zip object at 0x10aa0e848>
>>> list(zip(a,b,v)) # 把a片吊,b绽昏,v壓縮在一起
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> v = [7,8,9,10]
>>> list(zip(a,b,v)) # 如果數(shù)量不一樣多則會丟掉多余的,這里就把10丟掉了
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
解壓
>>> list(zip(a,b,v))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> ret = zip(a,b,c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> ret = zip(a,b,v)
>>> list(zip(*ret))
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]