-- coding: utf-8 --
@Time : 2019/11/7 8:56
@Author : Nix Chen
@Email : lethe4ever@163.com
@File : demo13_20191107.py
@Software: PyCharm
切片
對(duì)序列截取一部分的操作
字符串,列表,元組都支持切片操作
l1 = [i for i in range(10)]
print(l1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l1[2]) # 2
# 格式:對(duì)象[start:end:step] 左閉右開 省略 start代表從零開始,end代表包括最后,步長省略代表1
print(l1[2:7]) # [2, 3, 4, 5, 6]
print(l1[2:]) # [2, 3, 4, 5, 6, 7, 8, 9]
print(l1[0:4:2]) # [0, 2]
print(l1[0:2]) # [0, 1]
print(l1[-4:-2]) # [6, 7]
print(l1[-4:2]) # []
print(l1[-1:-3:-1]) # [9, 8]
print(l1[-1:1:-1]) # [9, 8, 7, 6, 5, 4, 3, 2]
print(l1[3:1:-1]) # [3, 2]
print(l1[3:-3:-1]) # []
print(l1[::]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l1[:]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l1[::2]) # [0, 2, 4, 6, 8]
# 反轉(zhuǎn)這個(gè)列表
print(l1[::-1]) # print(li[])
使用切片來原地修改列表的的內(nèi)容
a = [3, 5, 7]
a[len(a):] = [9]
print(a) # [3, 5, 7, 9]
a[:3] = [1, 2, 3]
print(a) # [1, 2, 3, 9]
a[:3] = []
print(a) # [9]
使用del 和 切片結(jié)合刪除列表的元素
a = [3, 5, 7, 9, 11]
del a[:3]
print(a) # [9, 11]
a = [3, 5, 7, 9, 11]
del a[::2]
print(a)
淺復(fù)制,是指生成一個(gè)新的列表,并且把原列表中的所有元素的引用都復(fù)制到這個(gè)新列表中
alist = [3, 5, 7]
blist = alist # 列表b與列表a指向同一塊內(nèi)存
print(id(alist)) # 19346496
print(id(blist)) # 19346496
blist[1] = 8
print(alist) # [3, 8, 7] 修改其中的一個(gè)對(duì)象會(huì)影響另外的一個(gè)對(duì)象
print(id(alist))
print(id(blist))
print(alist == blist) # == 是判斷兩個(gè)列表中的元素是否完全一樣 True
print(alist is blist) # 判斷兩個(gè)列表是否是同一個(gè)對(duì)象 True
alist = [3, 5, 7]
blist = alist[::] # 切片 淺復(fù)制,產(chǎn)生新的對(duì)象
print(blist) # [3, 5, 7]
print(alist == blist) # True
print(alist is blist) # Flase
print(id(alist)) # 76647080
print(id(blist)) #76820272
blist[1] = 8
print(alist) # [3, 5, 7]
結(jié)論 切片返回的是列表的元素的淺復(fù)制
id() 查看元素的內(nèi)存
== 判斷兩個(gè)對(duì)象中的元素是否完全一樣
is 判斷兩個(gè)列表是否是同一個(gè)對(duì)象
-- coding: utf-8 --
@Time : 2019/11/7 9:56
@Author : Nix Chen
@Email : lethe4ever@163.com
@File : demo14_20191107.py
@Software: PyCharm
元組 tuple
元組屬于不可變的序列,一旦創(chuàng)建用任何方法都不能將其修改()表示
a = (1, 2, 3)
print(type(a)) # <class 'tuple'>
一個(gè)元素的元組
x = (3)*4
print(type(x)) # <class 'int'>
print(x) # 12
x = (3, )*4
print(type(x)) # <class 'tuple'>
print(x) # (3, 3, 3, 3)
使用tuple函數(shù)將其他的序列轉(zhuǎn)換為元組
1.列表轉(zhuǎn)化成元組
from random import randint
a = [randint(-10, 10) for _ in range(10)]
print(a) #[10, 2, -9, -3, 2, 1, 0, 7, 7, -7]
a_tuple =tuple(a)
print(a_tuple) # (10, 2, -9, -3, 2, 1, 0, 7, 7, -7)
2.range函數(shù)
print(list(range(6))) # [0, 1, 2, 3, 4, 5]
print(tuple(range(6))) # (0, 1, 2, 3, 4, 5)
3.字符串
import string
print(string.ascii_lowercase[:7]) # abcdefg
t = tuple(string.ascii_lowercase[:7]) # ('a', 'b', 'c', 'd', 'e', 'f', 'g')
print(t)
l= list(string.ascii_lowercase[:7]) # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(l)
元組和列表的區(qū)別
1.元組中的數(shù)據(jù)一旦定義就不允許修改了
- 2.元組中沒有 append(), extend(), insert()等方法,不能向元組中添加元素*
3.元組中也沒有刪除的相關(guān)方法,不能從元組中刪除元素
4.從效果上看,tuple函數(shù)是凍結(jié)列表,list函數(shù)是融化列表
元組的優(yōu)點(diǎn)
元組的速度比列表塊
元組對(duì)數(shù)據(jù)進(jìn)項(xiàng)'寫保護(hù)',讓代碼更加安全
元組可以用做字典的鍵,還可以作為函數(shù)的返回值返回()
-- coding: utf-8 --
@Time : 2019/11/7 10:18
@Author : Nix Chen
@Email : lethe4ever@163.com
@File : demo15_20191107.py
@Software: PyCharm
字符串
字符串的切片
import string
letters = string.ascii_uppercase[:9]
print(letters) # ABCDEFGHI
print(letters[3]) # D
print(letters[2:4]) # CD
print(letters[:]) # ABCDEFGHI
print(letters[-2:]) # HI
print('letters[-2:2]', letters[-2:2]) # letters[-2:2]
print(letters[::-1]) # IHGFEDCBA
字符串常用操作方法
1.upper()..lower() 常用指數(shù)***
s1 = 'www.NEUEDU.com'
print(s1.upper()) # WWW.NEUEDU.COM
print(s1.lower()) # www.neuedu.com
2.startswith()..s1.endswith() 常用指數(shù)***
s1 = 'www.www.NEUEDU.com'
print(s1.startswith('www')) # 判斷是否以prefix開頭 True
print(s1.startswith('www', 4, 6)) # 左閉右開 False
print(s1.endswith('com')) # True
3.查找元素 find() index()
獲取制定元素首次出現(xiàn)的下標(biāo)
s1 = 'www.wwwNEUEDU.com'
print(s1.find('N')) # 7
print(s1.index('N')) # 7
print(s1.find('F')) # -1
# print(s1.index('F')) # index 找不到這個(gè)字符串會(huì)報(bào)錯(cuò)
print(s1.rfind('w')) # 6 獲取指定元素首次出現(xiàn)的下標(biāo),只不過是從右面開始
print(s1.rindex('w')) # 6
4.strip 默認(rèn)取出字符前后兩端的空格,換行符,tab 常用指數(shù) *****
rstrip() lsrip()
s1 = ' \n www.NEUEDU.com \t '
print(len(s1)) # 24
print(len(s1.strip())) # 14
s2 = 'aabbccddff'
s2 = s2.strip('aa')
print(s2) # bbccddff
s2 = s2.rstrip('ff') # 指定為右端
print(s2) # bbccdd
s2 = s2.lstrip('ff') # 指定為左端
print(s2) # 不做任何改變
5.split() 把字符串分割成列表,默認(rèn)是以空格進(jìn)行分割 常用指數(shù)*****
s1 = 'life is short, use Python'
print(s1.split()) # ['life', 'is', 'short,', 'use', 'Python'] 默認(rèn)以空格分割
print(s1.split(',')) # ['life is short', ' use Python']
s1 = 'life; is; short,; use; Python'
print(s1.split(';', 3)) # ['life', ' is', ' short,', ' use; Python']
print(s1.split(';', 1)) # 指定分隔多少個(gè) ['life', ' is; short,; use; Python']
print(s1.split(';',3)[3]) # use; Python
splitlines()
s2 = 'wwNEUw.\nwwwNEUEDU.com' # 按照行分隔,返回包含按照各行分隔為元素的列表
s2.rsplit()
s2.lstrip()
s2 = s2.splitlines()
print(s2)
6.join 把列表換成字符串 常用指數(shù)*****
s1 = 'life is short, use Python'
l1 = s1.split()
print(l1) # ['life', 'is', 'short,', 'use', 'Python'] # l1里面的元素全是字符串
s2 = ''.join(l1)
print(s2) # lifeisshort,usePython
s2 = ' '.join(l1)
print(s2) # life is short, use Python
s2 = '_'.join(l1)
print(s2) # life_is_short,_use_Python
s2 = '/'.join(l1)
print(s2) # life/is/short,/use/Python
s2 = '\\'.join(l1)
print(s2) # life\is\short,\use\Python
7.is系列 常用指數(shù)***
name = 'Neusoft123'
print(name.isalnum()) # 所有字符串是否都為數(shù)字或者字母 True
print(name.isdigit()) # 所有字符串是否都為數(shù)字 False
print(name.isalpha()) # 所有字符串是否都為字母 False
print(name.islower()) # 所有字符串是否都為小寫 False
print(name.isupper()) # 所有字符串是否都為大寫 False
print(name.istitle()) # 所有字符串是否都為首字母大寫 True
print(name.isspace()) # 所有字符串是否都為空白 False
8.count 計(jì)算某個(gè)字符出現(xiàn)的次數(shù) 常用指數(shù)***
name = 'Neusoft1233'
print(name.count('3')) # 2
9.replace 常用指數(shù)***** 替換指定的字符
name = 'Neusoft1233'
name = name.replace('1233','')
print(name) # Neusoft
name = '1233Neusoft1233'
name = name.replace('1233','',1)
print(name) # Neusoft1233
10.首字母大寫 常用指數(shù)**
name = 'neusoft1233'
print(name.capitalize()) # Neusoft1233
11.center 將字符串居中 常用指數(shù)*
參數(shù)可以設(shè)置字符串的總長度,可以使用*進(jìn)行填充
name = 'neusoft1233'
print(name.center(100,'*')) # ********************************************neusoft1233*********************************************
print(len(name.center(100,'*'))) # 100
ljust
s1 = 'neuedu'
print(len(s1)) # 6
print(s1.ljust(20))
print(s1.rjust(20))
print(len(s1.ljust(20))) #20
print(s1.ljust(20,'*'))
12.title 非字母隔開的每個(gè)單詞的首字母大寫 常用指數(shù)*
s = 'chen wuang4fhsa$.f'
print(s.title()) # Chen Wuang4Fhsa$.F
13.partition 將字符串分割成三部分
s1 = 'wwNEUw.www.NEUEDU.com'
print(s1.partition('NEU')) # 返回的是元組 ('ww', 'NEU', 'w.www.NEUEDU.com')
print(s1.rpartition('NEU')) # ('wwNEUw.www.', 'NEU', 'EDU.com')
-- coding: utf-8 --
@Time : 2019/11/7 14:24
@Author : Nix Chen
@Email : lethe4ever@163.com
@File : demo16_20191107.py
@Software: PyCharm
字典 包含若干鍵值的無需可變的序列,字典中的鍵可以為任意的不可變的數(shù)據(jù) 比如number,string,tuple
創(chuàng)建字典
d = {'server': 'db.neuedu.com', 'database': 'oracle'}
print(type(d)) # <class 'dict'>
print(d) # {'server': 'db.neuedu.com', 'database': 'oracle'}
空字典
d1 = {} # [] 空列表 () 不是空元組
d2 = dict()
print('d2', d2) # d2 {}
print(type(d1)) # <class 'dict'>
使用dict函數(shù)將已有數(shù)據(jù)轉(zhuǎn)化成字典
1.兩個(gè)列表
import string
keys = [x for x in string.ascii_lowercase[:5]]
print(keys) # ['a', 'b', 'c', 'd', 'e']
values = [i for i in range(1, 6)]
print(values) # [1, 2, 3, 4, 5]
print(dict(zip(keys, values))) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
2.使用dict()根據(jù)給定的鍵值創(chuàng)建
d3 = dict(name='wunan', age=18, gender= 'female')
print('d3',d3) # d3 {'name': 'wunan', 'age': 18, 'gender': 'female'}
3.根據(jù)給定的內(nèi)容為鍵,創(chuàng)建值為空的字典
print(dict.fromkeys(['name', 'age', 'gender'])) # {'name': None, 'age': None, 'gender': None}
字典的讀取
字典名的['鍵']
print(d3['name']) # wunan
# print(d3['addr']) # 以鍵作為下標(biāo)讀取字典元素,不存在這個(gè)鍵就會(huì)拋出異常
解決辦法: 使用字典的get方法獲取指定鍵對(duì)應(yīng)的值, 并且可以為不存在的鍵指定默認(rèn)值
print(d3.get('name')) # wunan
print(d3.get('addr')) # None
print(d3.get('addr', '內(nèi)蒙古通遼')) # 內(nèi)蒙古通遼
獲取字典所有的鍵 返回包含這個(gè)字典所有鍵的列表
print(list(d3.keys())) # ['name', 'age', 'gender']
獲取字典所有的值 返回包含這個(gè)字典所有值的列表
print(list(d3.values())) # ['wunan', 18, 'female']
獲取字典所有的鍵值 返回包含這個(gè)字典所有鍵值的列表
l3 = list(d3.items())
print(list(d3.items())) # [('name', 'wunan'), ('age', 18), ('gender', 'female')]
d4 = dict(l3)
print(d4) # {'name': 'wunan', 'age': 18, 'gender': 'female'}
字典的修改
print('d3',d3) # d3 {'name': 'wunan', 'age': 18, 'gender': 'female'}
# 字典名['鍵'] = '新的值'
d3['gender'] = 'male'
print(d3) # {'name': 'wunan', 'age': 18, 'gender': 'male'}
字典的添加
字典名['字典中不存在的鍵' ] = '新的值'
當(dāng)字典中存在這個(gè)鍵 就是修改操作
當(dāng)字典中不存在這個(gè)鍵 就是添加操作
d3['addr'] = '沈陽市渾南區(qū)新秀街'
print(d3) # {'name': 'wunan', 'age': 18, 'gender': 'male', 'addr': '沈陽市渾南區(qū)新秀街'}
字典的刪除
del 可以刪除整個(gè)字典,或者其中的指定元素
print(d3)
# del d3 # 字典完全被刪除
# print(d3) # 報(bào)錯(cuò)
根據(jù)鍵刪除整個(gè)元素
del d3['addr']
print(d3) # {'name': 'wunan', 'age': 18, 'gender': 'male'}
清除字典的所有數(shù)據(jù)
d3.clear()
print(d3) # {}
3. .pop() 刪除指定鍵所對(duì)應(yīng)的值,返回整個(gè)值并且從字典中把它刪除
ret = d3.pop('addr')
print(ret) # 沈陽市渾南區(qū)新秀街
print(d3) # {'name': 'wunan', 'age': 18, 'gender': 'male'}
按照后進(jìn)先出的順序,刪除字典的最后的鍵值對(duì),并無返回值
d3.popitem() # {'name': 'wunan', 'age': 18}
print(d3)
d3.popitem()
print(d3) # {'name': 'wunan'}
d3.popitem()
print(d3) # {}
判斷一個(gè)key 是否在字典中
print('name' in d3.keys()) # True
print('name' in d3) # True
字典的遍歷
遍歷所有的鍵
for key in d3.keys():
print(key)
for value in d3.values():
print(value)
for kv in d3.items():
print(kv) # 元組
遍歷所有的鍵值
for k, v in d3.items():
print(k, '---->', v)
-- coding: utf-8 --
@Time : 2019/11/7 15:20
@Author : Nix Chen
@Email : lethe4ever@163.com
@File : demo17_20191107.py
@Software: PyCharm
有序字典 可以使用collection模塊的
from collections import OrderedDict
創(chuàng)建一個(gè)無序字典
x = {}
x['b'] = 3
x['a'] = 1
x['c'] = 5
print(x) # {'b': 3, 'a': 1, 'c': 5}
x = OrderedDict()
x['b'] = 3
x['a'] = 1
x['c'] = 5
print(dict(x)) # {'b': 3, 'a': 1, 'c': 5}
字典推導(dǎo)式 (字典解析)
[i for i in range(10)]
{k: v for 臨時(shí)變量 in 可迭代對(duì)象 if 條件}
from random import randint
{'student1':90,'student2':90,'student3':90} 20名 學(xué)生
l1 = [randint(0,100) for x in range(1,21)]
grade = {'student{}'.format(x):randint(0, 100) for x in range(1,21)}
print(l1)
print(grade)
使用字典解析篩選 大于60分成績的學(xué)生
jige = {}
for k,v in grade.items():
if v > 60:
jige[k] = v
print(jige)
jige = {k:v for k,v in grade.items() if v>60}
print(jige)
-- coding: utf-8 --
@Time : 2019/11/7 16:21
@Author : Nix Chen
@Email : lethe4ever@163.com
@File : demo18_20191107.py
@Software: PyCharm
集合
無序不重復(fù)
只能包含不可變數(shù)據(jù)(數(shù)字,字符串,元組)
創(chuàng)建
a = {3,6,9}
print(type(a)) # <class 'set'>
print(a) # {9, 3, 6} 隨機(jī)順序
添加
a.add('8') # 數(shù)字,字符串,元組
print(a) # {9, 3, 6, '8'}
將其他類型數(shù)據(jù)轉(zhuǎn)化為集合
a = set(range(10))
print(a)
c = set([i for i in range(25)])
print(c)
# del c
# print(c) # name 'c' is not defined
update方法
d ={1, 2, 4}
d.update({5, 7, 4})
print(d) # {1, 2, 4, 5, 7}
pop() 彈出并刪除第一個(gè)元素
v =d.pop()
print(v) # 1
print(d) # {2, 4, 5, 7}
刪除指定元素的值
d.remove(5)
print(d) # {2, 4, 7}
清空集合
d.clear()
print(d) # set(), {}
使用集合快速提取序列中單一元素
from random import choice
# 隨機(jī)選取序列中的一個(gè)元素
print(choice(['a', 'b', 'c'])) # c
print(choice('dwfjio')) # d
random_list = [choice(range(100)) for _ in range(200)]
print(random_list) # [49, 12, 97, 4, 5, 49, 86, 41, 82, 39, 17, 13, 36, 58, 32, 38, 67, 82, 20, 18, 70, 87, 30, 68, 38, 52, 42, 17, 25, 24, 88, 67, 67, 34, 71, 12, 44, 35, 62, 16, 67, 41, 57, 23, 24, 60, 63, 98, 0, 52, 44, 37, 25, 84, 65, 2, 1, 0, 50, 49, 23, 56, 96, 14, 37, 60, 96, 7, 53, 69, 90, 8, 81, 61, 81, 18, 22, 43, 35, 59, 55, 83, 26, 18, 57, 58, 45, 1, 87, 81, 2, 87, 15, 23, 58, 46, 58, 32, 9, 86, 68, 65, 69, 55, 55, 28, 69, 16, 62, 32, 61, 66, 37, 63, 80, 94, 69, 5, 7, 39, 85, 58, 97, 57, 96, 2, 14, 96, 91, 55, 53, 87, 98, 13, 27, 92, 75, 0, 13, 12, 71, 24, 77, 99, 44, 18, 47, 17, 18, 61, 97, 10, 3, 66, 70, 63, 46, 5, 48, 29, 56, 12, 84, 1, 77, 99, 28, 45, 91, 10, 5, 0, 98, 33, 60, 42, 26, 89, 39, 97, 20, 95, 3, 3, 39, 4, 36, 31, 40, 61, 34, 98, 83, 10, 66, 4, 27, 52, 87, 98]
print((len(random_list))) # 200
# 生成一個(gè)norepeat的集合
noRepeat = []
for x in random_list:
noRepeat.append(x)
print(len(noRepeat)) # 200
noRepeat = set(noRepeat)
print(noRepeat) # {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 20, 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, 52, 53, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 70, 71, 75, 77, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 95, 96, 97, 98, 99}
.union, .intersection, .difference
集合的解析
將列表轉(zhuǎn)化為集合,并且做每個(gè)元素兩端去空格處理
s = [' ddd', ' is', ' python']
print({x.strip() for x in s }) # {'ddd', 'python', 'is'}