python變量賦值
常量 不變化的量紊服,比如數(shù)字膛檀,字符串都是
變量 存儲常量划乖,通常由變量名指出
賦值 就是將一個(gè)常量指向一個(gè)變量
name = 'while'
python是一門弱變量的語言族檬,所用變量即用即生成悲雳,變量的類型隨著值的類型的修改而修改
命名可用的內(nèi)容
字母
數(shù)字
下劃線
1. 數(shù)字不可以開頭拄丰,也不可以純數(shù)字
2. __開頭代表私有
3. __name__代表魔術(shù)方法
4. 關(guān)鍵字不可以用于命名
>>>import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
5. 命名要有意義晌端,禁止無意義的命名谚殊,比如戈鲁,a,a1,bb
常見的命名
名詞
name = 1
動賓結(jié)構(gòu)
get page = 1
getPage = 1
GetPage = 1
變量賦值的三種方式:
傳統(tǒng)賦值
name = 'while'
鏈?zhǔn)劫x值
name = user = 'while'
序列解包賦值
name,age = 'while',10
>>> name = 'while'
>>> name
'while'
>>> name = user = 'while'
>>> name,user
('while', 'while')
>>> name,age = 'shuai',18
>>> name,age
('shuai', 18)
>>> hello 變量不存在
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
hello
NameError: name 'hello' is not defined
>>> name,age = 'shuai',18,00 變量和常量不對應(yīng)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
name,age = 'shuai',18,00
ValueError: too many values to unpack (expected 2)
python列表
列表是一個(gè)元素以逗號分割仇参,以中括號包圍的,有序的婆殿,可修改的序列
python2
1诈乒、list
2、[]
3婆芦、range
4怕磨、xrange
python3
1、list
>>> list('abced')
['a', 'b', 'c', 'e', 'd']
>>> str(['a','b','c','d'])
"['a', 'b', 'c', 'd']"
>>> ''.join(['a','b','c'])
'abc'
2消约、[]
>>> ['a',1,[1,'a']]
['a', 1, [1, 'a']]
3肠鲫、range
>>> range(100)
range(0, 100)
>>> list(range(100))
[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]
>>> print(range(100))
range(0, 100)
列表的索引
列表的索引和字符串的索引類似,但不完全相同或粮,因?yàn)榱斜砜梢孕薷牡妓牵晕覀兛梢酝ㄟ^列表
的索引來修改列表
一樣的部分
>>> mylist = [1,2,3,45,6]
>>> mylist
[1, 2, 3, 45, 6]
>>> mylist1 = list('123456')
>>> mylist1
['1', '2', '3', '4', '5', '6']
>>> mylist[1]
2
>>> mylist[-1]
6
>>> mylist[:]
[1, 2, 3, 45, 6]
>>> mylist1[::2]
['1', '3', '5']
>>> mylist1[5:1:-1]
['6', '5', '4', '3']
>>> mylist1[1] = 's'
>>> mylist1
['1', 's', '3', '4', '5', '6']
超出索引范圍
>>> mylist1[100]
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
mylist1[100]
IndexError: list index out of range
列表的方法
列表的添加
append 追加,在列表的尾部加入指定的元素
extend 將指定序列的元素依次追加到列表的尾部
insert 將指定的元素插入到對應(yīng)的索引位上,注意負(fù)索引
列表的刪除
pop 彈出渣锦,返回并刪除指定索引位上的數(shù)據(jù)硝岗,默認(rèn)-1
remove 從左往右刪除一個(gè)指定的元素
del 刪除是python內(nèi)置功能,不是列表獨(dú)有的
列表的查找
注 列表沒有find方法
count 計(jì)數(shù)袋毙,返回要計(jì)數(shù)的元素在列表當(dāng)中的個(gè)數(shù)
index
查找型檀,從左往右返回查找到的第一個(gè)指定元素的索引,如果沒有找到听盖,報(bào)錯(cuò)
列表的排序
reverse 索引順序倒序
sort 按照ascii碼表順序進(jìn)行排序
append 列表末尾添加
>>> mylist = list('1a23456')
>>> mylist
['1', 'a', '2', '3', '4', '5', '6']
>>> mylist.append('a')
>>> mylist
['1', 'a', '2', '3', '4', '5', '6', 'a']
>>> mylist.append([123])
>>> mylist
['1', 'a', '2', '3', '4', '5', '6', 'a', [123]]
>>> mylist.append('[123]')
>>> mylist
['1', 'a', '2', '3', '4', '5', '6', 'a', [123], '[123]']
extend 將序列直接添加到末尾
>>> mylist = list('123456')
>>> mylist
['1', '2', '3', '4', '5', '6']
>>> mylist.extend('123')
>>> mylist
['1', '2', '3', '4', '5', '6', '1', '2', '3']
insert 將元素直接添加到指定位置
>>> mylist.insert('a',0) 注意順序
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
mylist.insert('a',0)
TypeError: 'str' object cannot be interpreted as an integer
>>> mylist.insert(0,'a')
pop 默認(rèn)彈出最后一個(gè)位置胀溺,可以指定彈出的元素
>>> mylist
['a', '1', '2', '3', '4', '5', '6', '1', '2', '3']
>>> mylist.pop()
'3'
>>> mylist
['a', '1', '2', '3', '4', '5', '6', '1', '2']
>>> mylist.pop()
'2'
>>> mylist
['a', '1', '2', '3', '4', '5', '6', '1']
>>> list(mylist)
['a', '1', '2', '3', '4', '5', '6', '1']
>>> mylist.pop(0) 彈出指定位置的元素
'a'
remove 從左往右刪除指定的元素,一次刪除一個(gè)
>>> mylist
['1', '2', '3', '4', '5', '6', '1']
>>> mylist.remove(1)
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
mylist.remove(1)
ValueError: list.remove(x): x not in list
>>> mylist.remove('1')
>>> mylist
['2', '3', '4', '5', '6', '1']
del 刪除指定位置的元素
>>> del mylist[1]
>>> mylist
['2', '4', '5', '6', '1']
>>> del mylist[0]
>>> mylist
['4', '5', '6', '1']
>>> del mylist('1')
SyntaxError: can't delete function call
>>> del mylist
>>> mylist
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
mylist
NameError: name 'mylist' is not defined
count 尋找指定元素的個(gè)數(shù) #注意list方法和[]這個(gè)的區(qū)別
一個(gè)是字符串一個(gè)是數(shù)字 使用函數(shù)的方法也不一樣
>>> mylist = list('12345')
>>> mylist
['1', '2', '3', '4', '5']
>>> mylist.count(0)
0
>>> mylist.count(1)
0
>>> mylist.count(2)
0
>>> mylist = list('1234566')
>>> mylist
['1', '2', '3', '4', '5', '6', '6']
>>> mylist.count(6)
0
>>> mylist.count('6')
2
>>> mylist = [1,2,3,4]
>>> mylist.count(1)
1
>>> mylist
[1, 2, 3, 4]
index 從左往右尋找指定元素的索引媳溺,第一個(gè)元素
>>> mylist
[1, 2, 3, 4]
>>> mylist.index(1)
0
>>> mylist.index(2)
1
>>> mylist.index(3)
2
>>> mylist = list('1234')
>>> mylist.index('1')
0
>>> mylist.index(1)
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
mylist.index(1)
ValueError: 1 is not in list
reverse 按照索引順序進(jìn)行倒序
>>> mylist
['1', '2', '3', '4']
>>> mylist.reverse()
>>> mylist
['4', '3', '2', '1']
>>> mylist = list('dadgasgreaghfdah')
>>> mylist
['d', 'a', 'd', 'g', 'a', 's', 'g', 'r', 'e', 'a', 'g', 'h', 'f',
'd', 'a', 'h']
>>> mylist.reverse()
>>> mylist
['h', 'a', 'd', 'f', 'h', 'g', 'a', 'e', 'r', 'g', 's', 'a', 'g',
'd', 'a', 'd']
sort 直接按照ascii碼排序月幌,不能數(shù)字和字符一起排序
>>> mylist
['h', 'a', 'd', 'f', 'h', 'g', 'a', 'e', 'r', 'g', 's', 'a', 'g', 'd', 'a', 'd']
>>> mylist.sort()
>>> mylist
['a', 'a', 'a', 'a', 'd', 'd', 'd', 'e', 'f', 'g', 'g', 'g', 'h', 'h', 'r', 's']
>>> mylist = [1,2,3,4]
>>> mylist.sort()
>>> mylist
[1, 2, 3, 4]
>>> mylist = [1,'a',2,3]
>>> mylist
[1, 'a', 2, 3]
>>> mylist.sort()
Traceback (most recent call last):
File "<pyshell#109>", line 1, in <module>
mylist.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
>>> mylist = [1,2,3,'1']
>>> mylist.sort()
Traceback (most recent call last):
File "<pyshell#111>", line 1, in <module>
mylist.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
python元組
元組是元素以逗號分割碍讯,以小括號包圍的有序的悬蔽,不可修改的序列
tuple()
構(gòu)建元組的方法
>>> mytuple = tuple('12345')
>>> mytuple
('1', '2', '3', '4', '5')
>>> ('a',1,3)
('a', 1, 3)
元組的索引和字符串是一樣的
>>> mytuple
('1', '2', '3', '4', '5')
>>> mytuple.count('1')
1
>>> mytuple.count(2)
0
>>> mytuple.count('2')
1
>>> mytuple.count('1')
1
>>> mytuple.count('3')
1
>>> mytuple[::-1]
('5', '4', '3', '2', '1')
>>> mytuple[-1]
'5'
>>> mytuple
('1', '2', '3', '4', '5')
>>> mytuple[1]
'2'
>>> mytuple[0:3]
('1', '2', '3')
>>> mytuple[5:0:-1]
('5', '4', '3', '2')
>>> mytuple[5::-1]
('5', '4', '3', '2', '1')
元組的特性
元組可以不加括號
>>> 1,2
(1, 2)
單元素元組需要加逗號
>>> type([1])
<class 'list'>
>>> type((1))
<class 'int'>
>>> type((21,))
<class 'tuple'>
元組不可修改,所以我們再配置文件中多看到元組
Django 配置的一部分
DATABASE = (
Os.path.join(BASEDIR," TEMPLATE"),
)
元組的方法
元組的查找
index 從左往右指定元素的索引捉兴,遇見的第一個(gè)元素
count 尋找元組中的指定的元素的個(gè)數(shù)
>>> mytuple
('1', '2', '3', '4', '5')
>>> mytuple.index('1')
0
>>> mytuple.index('5')
4
>>> mytuple.count('1')
1
>>> mytuple.count('5')
1
元組和字符串的區(qū)別
1蝎困、元組和字符串都是有序的,不可修改的序列
2倍啥、元組的元素可以是任何類型禾乘,字符串的元素只能是字符
3、元組的元素長度可以任意虽缕,字符串的元素長度只能為 1
驗(yàn)證元組和字符串的長度
>>> a
'abc'
>>> mytuple
'shuai'
>>> len(a[0])
1
>>> len(mytuple[0])
1
>>> mytuple = ('shuai',1)
>>> mytuple
('shuai', 1)
>>> len(mytuple[0])
5
元組的創(chuàng)建方法
>>> a
'shuai'
>>> mytuple = ('shuai',a)
>>> mytuple
('shuai', 'shuai')
>>> mytuple = ('shuai',1)
>>> mytuple
('shuai', 1)
>>> len(mytuple[0])
5
>>> mytuple = ('shuai',a) a = 'shuai'
>>> mytuple
('shuai', 'shuai')
>>> len(mytuple[0])
5
>>> mytuple = ('shuai',b) 引入字符串必須放在引號里
Traceback (most recent call last):
File "<pyshell#196>", line 1, in <module>
mytuple = ('shuai',b)
NameError: name 'b' is not defined
>>> mytuple = ('shuai','b')
>>> mytuple
('shuai', 'b')
>>> mytuple = ('shuai',1) 數(shù)字可以放在外面
>>> mytuple
('shuai', 1)
>>> mytuple = ('shuai',)
>>> mytuple
('shuai',)
>>> len(mytuple[0])
5
>>> mytuple = ('shuai,shuai') 與這個(gè)區(qū)分始藕,這是字符串的創(chuàng)建方法
python字典
字典一個(gè)元素呈鍵值對的形式,以逗號分割氮趋,以大括號包圍的無序的伍派,可以修改的序列。
字典是python基礎(chǔ)數(shù)據(jù)類型當(dāng)中唯一一個(gè)映射關(guān)系的數(shù)據(jù)類型剩胁,通常對應(yīng)JSON{}
字典創(chuàng)建方法
>>> mydict = {'a':1,"b":2}
>>> mydict
{'a': 1, 'b': 2}
fromkeys 這種方法只能給所有的鍵都賦一樣的值
>>> mydict = {}.fromkeys('abcd')
>>> mydict
{'a': None, 'b': None, 'c': None, 'd': None}
>>> mydict = {}.fromkeys('abcd','shuai')
>>> mydict
{'a': 'shuai', 'b': 'shuai', 'c': 'shuai', 'd': 'shuai'}
dict
zip
函數(shù):將幾個(gè)序列對應(yīng)索引位上的元素分到一個(gè)元組中诉植,總的形成一個(gè)列表,子元組的
個(gè)數(shù)取決于提供的序列的最小長度
python2 與python3的區(qū)別
python2 直接返回對象
python3 返回對象的內(nèi)存地址昵观,需要用列表進(jìn)行轉(zhuǎn)換
補(bǔ)充:python3中減少了內(nèi)存的占用晾腔,優(yōu)化了性能但是速度更慢了
>>> myzip = zip('abcd','1234')
>>> myzip
<zip object at 0x00000223D8276BC8> python3中的內(nèi)存地址
>>> list(myzip)
元素啄一對應(yīng),長度取決于最小的序列的長度
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
>>> myzip = zip('abcd','123456','shuai','1234')
>>> myzip
<zip object at 0x00000223D828A388>
>>> list(myzip)
[('a', '1', 's', '1'), ('b', '2', 'h', '2'), ('c', '3', 'u',
'3'), ('d', '4', 'a', '4')]
>>> dict([('a',1),('b',2)])
{'a': 1, 'b': 2}
>>> dict(zip('abcdefg','1234567'))
{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5', 'f': '6', 'g': '7'}
>>> mydict = zip('abcd','1234')
>>> mydict
<zip object at 0x00000223D828AE08>
>>> list(mydict)
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
>>> mydict = dict(mydict)
>>> mydict
{}
>>> mydict = zip('abcd','1234')
>>> mydict = dict(mydict)
>>> mydict
{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
>>> mydict = zip('abcd','1234')
>>> mydict
<zip object at 0x0000018304BCF2C8>
>>> list(mydict)
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
>>> dict(mydict)
{}
>>> mydict = zip('abcd','1234')
>>> dict(mydict)
{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
mydict = zip('') 創(chuàng)建的是列表
dict(zip()) 列表轉(zhuǎn)為字典
dict([()]) 元組-->列表-->字典
字典的特點(diǎn):
因?yàn)樽值涫菬o序的啊犬,所以字典沒有索引值
因?yàn)樽值錄]有索引值灼擂,所以字典以鍵取值,(字典的鍵相當(dāng)于列表的索引)
>>> myzip = dict(zip('abcd','1234'))
>>> myzip
{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
>>> myzip['a']
'1'
因?yàn)樽值湟枣I取值觉至,所以字典的鍵唯一且不可修改剔应。
因?yàn)樽值涞逆I不可修改,所以列表和字典不可以給字典做鍵。
>>> myzip = {'a':1,1:'a',(1,2):'c'}
>>> myzip
{'a': 1, 1: 'a', (1, 2): 'c'}
>>> myzip = {'a':1,1:'a',(1,2):'c',{'a':1}:1}
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
myzip = {'a':1,1:'a',(1,2):'c',{'a':1}:1}
TypeError: unhashable type: 'dict'
字典和列表不可以作為字典的鍵
字典的方法:
字典的取值:
keys 獲取字典所有的鍵
values 獲取字典所有的值
get 以鍵取值领斥,如果指定鍵不存在嫉到,默認(rèn)返回None可以指定返回內(nèi)容
update 更新指定鍵的內(nèi)容,如果鍵不存在就直接創(chuàng)建
setdefault 設(shè)置默認(rèn)月洛,如果鍵存在何恶,返回值,如果鍵不存在嚼黔,創(chuàng)造鍵细层,值默認(rèn)
為None,值也可以自定義
items 返回字典鍵值呈元組形式的格式
字典的刪除
pop 彈出唬涧,返回并刪除指定鍵對應(yīng)的值
popitem 隨機(jī)彈出一個(gè)鍵值元組疫赎,這里隨機(jī)的原因是因?yàn)樽值錈o序
clear 清空字典
字典的取值
>>> mydict = dict(zip('abc','123'))
>>> mydict
{'a': '1', 'b': '2', 'c': '3'}
keys
>>> mydict.keys()
dict_keys(['a', 'b', 'c'])
values
>>> mydict.values()
dict_values(['1', '2', '3'])
>>> list(mydict.keys())
['a', 'b', 'c']
>>> list(mydict.values())
['1', '2', '3']
>>> mydict.get('a')
'1'
>>> mydict['a']
'1'
>>> mydict.get('x')
>>> mydict['x']
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
mydict['x']
KeyError: 'x'
>>> mydict.update(dict(zip('a',1)))
Traceback (most recent call last):
File "<pyshell#75>", line 1, in <module>
mydict.update(dict(zip('a',1)))
TypeError: zip argument #2 must support iteration
>>> mydict.update({'a',1})
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
mydict.update({'a',1})
TypeError: cannot convert dictionary update sequence element #0 to a sequence
>>> mydict
{'a': '1', 'b': '2', 'c': '3'}
>>> mydict.update({'a':1})
>>> mydict
{'a': 1, 'b': '2', 'c': '3'}
>>> mydict.update({'a':2})
>>> mydict
{'a': 2, 'b': '2', 'c': '3'}
>>> mydict+{'y':1}
Traceback (most recent call last):
File "<pyshell#83>", line 1, in <module>
mydict+{'y':1}
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> mydict.update({'x':55})
>>> mydict
{'a': 2, 'b': '2', 'c': '3', 'x': 55}
>>> mydict.setdefault('x')
55
>>> mydict.setdefault('y')
>>> mydict
{'a': 2, 'b': '2', 'c': '3', 'x': 55, 'y': None}
>>> mydict.setdefault('y',88)
>>> mydict
{'a': 2, 'b': '2', 'c': '3', 'x': 55, 'y': None}
>>> mydict.setdefault('h',99)
99
>>> mydict
{'a': 2, 'b': '2', 'c': '3', 'x': 55, 'y': None, 'h': 99}
>>> mydict.items()
dict_items([('a', 2), ('b', '2'), ('c', '3'), ('x', 55),
('y', None), ('h', 99)])
>>> list(mydict.items())
[('a', 2), ('b', '2'), ('c', '3'), ('x', 55), ('y',
None), ('h', 99)]
>>>
字典的刪除
pop 只能彈出指定的內(nèi)容鍵,不能彈出數(shù)值
>>> mydict.pop()
Traceback (most recent call last):
File "<pyshell#96>", line 1, in <module>
mydict.pop()
TypeError: pop expected at least 1 arguments, got 0
>>> mydict.pop('y')
>>> mydict
{'a': 2, 'b': '2', 'c': '3', 'x': 55, 'h': 99}
>>> mydict.pop('h')
99
>>> mydict
{'a': 2, 'b': '2', 'c': '3', 'x': 55}
>>> mydict.pop(55)
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
mydict.pop(55)
KeyError: 55
popitem clear 隨機(jī)彈出內(nèi)容碎节,清空內(nèi)容
>>> mydict
{'a': 2, 'b': '2', 'c': '3', 'x': 55}
>>> mydict.popitem()
('x', 55)
>>> mydict.popitem()
('c', '3')
>>> mydict.popitem()
('b', '2')
>>> mydict
{'a': 2}
>>> list(mydict.items())
[('a', 2)]
>>> mydict = dict(zip('abcd','1234'))
>>> mydict
{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
>>> list(mydict.items())
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
>>> mydict.popitem()
('d', '4')
>>> mydict.popitem()
('c', '3')
>>> mydict.popitem()
('b', '2')
>>> mydict
{'a': '1'}
>>> mydict.clear()
>>> mydict
{}
python2中
判斷has_key
python3
用in 替換
in判定有沒有指定的鍵
>>> mydict = dict(zip('abcd','1234'))
>>> mydict
{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
>>> 'a' in mydict 判斷a 是否在字典里
True
>>> 2 in mydict
False
>>> '2' in mydict
False
字典的拷貝屬于淺層拷貝捧搞,拷貝和拷貝對象的嵌套層同屬一個(gè)內(nèi)存,一個(gè)修改另一個(gè)也會修改
普通鍵對應(yīng)的值發(fā)生變化狮荔,復(fù)制的字典值不變胎撇,列表對應(yīng)的鍵值變了,復(fù)制的列表的對應(yīng)的鍵值也變化
>>> mydict
{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
>>> mydict.update({'z':[11]})
>>> mydict
{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'z': [11]}
>>> mydict_1 = mydict.copy()
>>> mydict_1
{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'z': [11]}
>>> mydict['a'] = 11
>>> mydict
{'a': 11, 'b': '2', 'c': '3', 'd': '4', 'z': [11]}
>>> mydict_1
{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'z': [11]}
>>> mydict['z'][0] = 5
>>> mydict
{'a': 11, 'b': '2', 'c': '3', 'd': '4', 'z': [5]}
>>> mydict_1
{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'z': [5]}
數(shù)據(jù)類型的總結(jié)
str list tuple dict
是否有序 是 是 是 否
是否可修改 不 可 不 可
方法多少 很多 一般 很少 較多 映射關(guān)系