#python數據結構(list)
## 分類
數值型:int、float、complex、bool
序列對象:字符串 str ? 列表 ?list ? 元組 ?tuple
鍵值對: 集合 set ? 字典 dict
## 數字的處理函數
math.e ?math.pi: 自如常數和π
round(): ?四舍六入五去偶
floor(): ?取整數位
ceil(): 整數位 +1
min(): 取最小的那個
max(): 取最大的那個
pow(): 等于x**y
math.sqrt(): 取根號
bin() ?oct() ?hex() : 二進制、八進制、十六進制
## 類型判斷
type(object) ?, 返回類型,不是字符串
isinstance(object , class_or_tuple) ? ?例如: ?isinstance(‘a’ , int) ?返回的是False
## 列表list
定義:列表是一個隊列,有若干個元素組成,可以是任意對象(數字、字符串、對象、列表),并且是可變的
lst = list() ? ? lst = [] ? ? lst = [1,2,3,’abc’] ? ? lst = list(range(5))
列表索引訪問:
正索引:從左到右,從0開始,為列表中每一個元素編號
負索引:從右到左,從-1開始
list[index],列表通過索引可以訪問,使用中括號。
列表查詢:
index(value,[start,[stop]]):從指定區間查找匹配的元素,匹配到第一個就立即返回索引。
count(value) 返回列表中匹配的次數
時間復雜度:O(1) 、O(n) 、O(n^2)、O(n^3),n越大耗時越長,效率越低。
len():返回列表元素的個數
列表元素的修改:
list[index] = value
列表增加、插入元素
list1.append(object) ? ?時間復雜度O(1)
list1.insert(index,object) ? ?時間復雜度O(1)
list1.extend(list2) ? 將可迭代對象元素追加進來,就地修改
list1 + list2 ?連接操作,將兩個列表連接起來,產生新的列表,原列表不變
list1*5 ?本列表中的元素將重5次,返回新的列表
列表刪除元素
remove(value):從左至右查找第一個匹配value的值,并移除該元素,返回None,就地修改
list1.pop([index]):不指定索引就從尾部彈出一個元素,指定索引就從索引處彈出元素
list1.clear():清除列表中的所有元素,剩下一個空列表
列表其他操作
list1.reverse():將列表反轉,就地修改
list1.sort(key=None,reverse=False):對列表進行排序,就地修改,默認升序;reverse為True,反轉,降序。key一個函數,指定key排序。
列表復制
list2 = list1.copy() ? 返回一個新列表
shadow copy:淺拷貝,遇到引用類型,只復制一個引用而已
lst5 = copy.deepcopy(lst0) :深拷貝。重新創建一個新的列表,讓lst5指向它
隨機數
random模塊
randint(a,b):返回[a,b]之間的整數
choice(seq) ?: 從非空序列的元素中挑選一個 ? ?random.choice(range(10)),從0到9中隨機挑選一個整數[1,3,5,7]
randrange([start,] stop [,step]) 按指定基數遞增的集合中獲取一個隨機數。例如:random.randage(1,7,2)
random.shuffle(list):就地打亂列表元素。
## 數列解決100以內素數問題
import?math
prime?=?[]
flag?=?False
for?i?in?range(2,100):
for?j?in?prime:
if?i%j?==?0:
flag?=?True
break
if?j?>=?math.ceil(math.sqrt(i)):
flag?=?False
break
if?not?flag:
prime.append(i)
print(prime)
## 楊輝三角
法1:
triangle?=?[]
n?=?6
for?i?in?range(n):
if?i?==?0:
triangle.append([1])
else:
pre?=?triangle[i-1]
cur?=?[1]
for?j?in?range(0,i-1):
cur.append(pre[j]+pre[j+1])
cur.append(1)
triangle.append(cur)
print(triangle)
法1(2):
tri?=?[]
n?=?6
for?i?in?range(n):
row?=?[1]
tri.append(row)
if?i?==?0:
continue
for?j?in?range(i-1):
row.append(tri[i-1][j]?+?tri[i-1][j+1])
row.append(1)
print(tri)
法2:
n = 6
oldline = []
newline = [1]
length = 0
print(newline)
for i in range(1, n):
oldline = newline.copy()
oldline.append(0)
newline.clear()
for j in range(i+1):
newline.append(oldline[j-1] + oldline[j])
print(newline)
法3 ?:
triangle = []
n = 6
for i in range(n):
row = [1]*(i+1)
triangle.append(row)
if i == 0:
continue
for j in range(1,i//2+1):
val = triangle[i – 1][j-1] + triangle[i – 1][j]
row[j] = val
if j != i – j: ? ? ? ? ? ? ? ? #判斷要不要對稱復制
row[-j-1] = val
print(triangle)
# python數據結構(tuple)
## ? 元組定義
元組是一個有序的元素組成的集合,()表示,元組是不可變對象。
t = (22,) ? t = (2,)*7 ? t = (1,2,3)*6
元組查詢和元素索引訪問與列表相似
## ? 命名元組namedtuple
from collections import namedtuple
Point = namedtuple(‘Point’,[‘x’,’y’])
p = Point(11,22)
>>> p.x = 11 ? ?p.y = 22
Student = namedtuple(‘Student’,’name age’)
tony = Student(‘tony’,17)
petter = Student(‘petter’,18)
>>>petter.name = petter
## ?冒泡法
時間復雜度O(n^2)
num = [1,9,3,5,7,6,8,2,4]
for i in range(len(num)):
flag = False
for j in range(len(num)-i-1):
if num[j] > num[j+1]:
tmp = num[j]
num[j] = num[j+1]
num[j+1] = tmp
flag = True
if not flag: #為了判斷是否在前一步就已經完成
break
print(num)
# ?字符串
## 字符串定義
字符串由一個個字符組成的序列,使用單雙三引號引住,具有不可變屬性
s1 = ‘string’ ? s2 = r’hello \n magedu.com’
## 字符串連接
“string”.join(iterable)
例如:lst = [‘1′,’2′,’3’]
## ?字符串分割
split:將字符串按照分隔符分割成若干字符串,并返回列表
partition:將字符串按照分隔符分割成2段,返回這2段和分隔符的元組
## ?字符串判斷
s.startswith(‘very’,5) ? ? ? ? >>>True
s.endswith(‘very’,5) ? ? ? ? ?>>> False
s.endswith(‘sorry’,5,-1) ? ? >>>False
## ?字符串判斷
isalnum() ?判斷是否是字母數字組成
isalpha() ?判斷是否是字母
isdecimal() 是否只包含十進制
isdigit() 是否全部數字
isidentifier() 判斷是不是標識符
islower() ?是否小寫
isupper() 是否大寫
isspace() ?是否空格字符
## ?字符格式化
“{}{}”.format(*args,**kwargs) ? ? #arg是一個元組
“{}:{}”.format(‘192.168.1.100’,8888)
“{server} {1}:{0}”.format(8888, ‘192.168.1.100’, server=’Web Server Info : ‘)
訪問元素:
“{0[0]}.{0[1]}”.format((‘magedu’,’com’))
對象屬性訪問:
from collections import namedtuple
Point = namedtuple(‘Point’,’x y’)
p = Point(4,5)
“{{{0.x},{0.y}}}”.format(p)
對齊:
‘{0}*{1}={2:<2}’.format(3,2,2*3)
‘{0}*{1}={2:<02}’.format(3,2,2*3)
‘{0}*{1}={2:>02}’.format(3,2,2*3)
進制:
octets = [192, 168, 0, 1]
‘{:02X}{:02X}{:02X}{:02X}’.format(*octets)
## ?練習
輸入一串數字,判斷是幾位數字,打印每一位數字及其重復的次數,一次打印個十百千萬位
num = “”
print(‘請輸入一個數字’)
while True:
num = input().strip().lstrip(‘0’)
if num.isdigit():
break
else:
print(‘不合規范重新輸入’)
print(‘{}’.format(len(num)))
count = [0]*10
for i in range(10):
count[i] = num.count(str(i))
for i in range(10):
if count[i]:
print(‘數字{}出現的次數是{}’.format(i,count[i]))
lst = list(num)
lst.reverse()
print(lst)?
## ?倒序打印
(1)
for i in range(len(num),0,-1):
print(i,end = ‘ ‘)
print()
(2)
for i in reversed(num):
print(i,end=’ ‘)
print()
(3) ?負索引打印
for i in range(len(num)):
print(num[-i-1],end=” “)
print()
## ? 判斷0-9的字數在字符串中出現的次數。
(1) ?迭代字符串中本身的字符
counter = [0]*10
for x in num:
i = int(x)
if counter[i] == 0:
counter[i] = num.count(x)
print(“The count of {} is {}”.format(x,counter[i]))
(2) ? 迭代字符串本身的字符
counter = [0]*10
for x in num:
i = int(x)
counter[i] += 1
for i in range(len(counter)):
if counter[i]:
print(“The count of {} is {}”.format(i,counter[i]))
## ?bytes 、bytearry
bytes:不可變字節序列
bytearray:字節數組,可變
編碼:字符串按照不同的字符集編碼encode返回字節序列bytes
encode(encoding = ‘utf – 8’,error = ‘strict’)
解碼:字節序列按照不同的字符集解碼decode返回字符串
bytes.decode(encoding=’utf – 8′,error = ”strict)
bytearray.decode(encoding=’utf – 8′,error = ”strict)
bytes(string,encoding) ?等價于 ?string.encode()
用法: 和str類似
b’abcdef’.replace(b’f’,b’k’)
b’abc’.find(b’b’)
bytes.fromhex(string) ? —->>返回字符串
‘abc’.encode().hex() ? —->> ?返回一個十六進制數
索引:b’abcdef'[2],返回該字節對應的數。int類型
bytearray操作:
與bytes類型的方法相同
bytearray(b’abcdef’).replace(b’f’,b’g’)
bytearray(b’abcdef’).find(b’f’) ? ——->> 返回5
hex():
bytearray.fromhex(‘6162 09 6a 6b00’)
bytearray(‘abc’.encode()).hex()
索引:
bytearray(b’abcdef’)[2] ? —–>>返回int類型對應的數
內置操作:
append(),insert(),extend(),pop(),remove() 用法與list相似 ?PS:(使用時int類型)
clear() 清空, reverse() 反轉,就地修改
## ? 切片操作( 方向向右為正,否則步長為負 )
線性結構:可迭代for…in…
len()方法獲取長度
通過下標可以訪問
‘www.magedu.com’[4:10] ? ? >>>magedu
‘www.magedu.com’[4:10] ? ? >>>www.magedu
b’www.magedu.com'[-40:10] ?>>>b’www.magedu’
bytearray(b’www.magedu.com’)[-4:-10:-2] ? >>>bytearray(b’.dg’)
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/87533