python基礎set

來源:互聯網
上載者:User

標籤:rom   image   turn   運算   ace   count   大寫   發送郵件   isa   

 

1、set

set是一個無序不重複的集合

li=[11,22,33,11]s=set(li)print(s){11,22,33}

 set提供的方法

1、add(self*args, **kwargs):   添加

li={11,22,33}s=li.add(44)print(li){11,22,33,44}

 2、clear(self*args, **kwargs):  清除內容

li={11,22,33,44}s=li.clear()print(li)str()

 3、difference(self*args, **kwargs):  尋找不同 s=A.different(B)  A中存在的B中不存在的元素賦值給s

li={11,22,33,44,11}l2={22,44,55,11}s=li.difference(l2)print(s){33}

 4、difference_update(self*args, **kwargs): 把不同找到並更新原有的  s=A.difference_update(B)  A中存在的B中不存在的元素找到並更新A

li={11,22,33,44}l2={11,22,33,55}li.different_upper(l2)print(li){44}

 

5、discard(self*args, **kwargs):  移除指定元素  不存在不報錯

li={11,22,33,44}s=li.discard(11)print(li){22,33,44}

 6、intersection(self*args, **kwargs): 尋找相同 s=A.intersection(B)  A、B中都存在的元素賦值給s

li={11,22,33,44}l2={11,22,44}s=li.intersection(l2)print(s){11,22,44}

 7、intersection_update(self*args, **kwargs):  把相同的找到並更新原有的  s=A.intersection_update(B)  AB中都存在的元素找到並更新A

li={11,22,33,44}l2={11,22,44}s=li.intersection_update(l2)print(li){11,22,44}

 8、isdisjoint(self*args, **kwargs): 查看倆個集合有沒有交集 如果有則返回False 沒有返回True

li={11,22,33,44}l2={00,77}s=li.isdisjoint(l2)print(s)True

 9、issubset(self*args, **kwargs):  是否是子序列

li={11,22,33,44}l2={00,77}s=li.issubset(l2)print(s)False

 10、 issuperset(self*args, **kwargs): 是否是父序列

li={11,22,33,44}l2={00,77}s=li.issuperset(l2)print(s)False

 11、pop(self*args, **kwargs):  隨機移除並賦值

li={11,22,33,44}s=li.pop()print(s){33}

 12、remove(self*args, **kwargs):  移除指定元素 不存在則報錯

li={11,22,33,44}s=li.remove(11)print(li){22,33,44}

 13、symmetric_difference(self*args, **kwargs):   s=A.symmetric_difference(B)把A中有B中無得元素和B中有A中無得元素放到s中

li={11,22,33,44}l2={11,55,66,77}s=li.symmetric_difference(l2)print(s){33, 66, 44, 77, 22, 55}

 

14、symmetric_difference_update(self*args, **kwargs):   s=A.symmetric_difference_update(B)把A中有B中無得元素和B中有A中無得元素賦值給s

li={11,22,33,44}l2={11,55,66,77}s=li.symmetric_difference_update(l2)print(li){22,33,44,55,66,77}

 15、union(self*args, **kwargs): 並集

li={11,22,33,44}l2={11,55,66,77}s=li.union(l2)print(s){11,22,33,44,55,66,77}

 16、update(self*args, **kwargs):  更新  不會產生新的集合

li={11,22,33,44}l2={11,55,66,77}s=li.update(l2)print(li){11,22,33,44,55,66,77}

 練習題

# 資料庫中原有old_dict = {    "#1":{ ‘hostname‘:c1, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 },    "#2":{ ‘hostname‘:c1, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 }    "#3":{ ‘hostname‘:c1, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 }}   # cmdb 新彙報的資料new_dict = {    "#1":{ ‘hostname‘:c1, ‘cpu_count‘: 2, ‘mem_capicity‘: 800 },    "#3":{ ‘hostname‘:c1, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 }    "#4":{ ‘hostname‘:c2, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 }}
m=set(old_dict.keys())
print(m)
n=set(new_dict.keys())
print(n)

需要添加的  a=n.different(m)

需要刪除的  b=m.different(n)

需要更新的  c=m.intersection(n)

old_dict.update(a)

print(old_dict)

old_dict.pop(b)

print(old_dict)

6、三元運算(三目運算),是對簡單的條件陳述式的縮寫

 書寫格式:   a=  值1 if  條件  else  值2     如果條件成立則把值1賦值給a  條件不成立把值2賦值給a

a="lu" if 1>2 else "xiao"print(a)xiao

7、深淺拷貝

字串(str)一次性建立,不能被修改。只要修改則再建立產生新的

列表(list)鏈表 可以記錄上及下的位置

數值和字串

只要是賦值,拷貝(無論深淺)地址都一樣

其他資料類型

 對於字典、元祖、列表 而言,進行賦值、淺拷貝和深拷貝時,其記憶體位址的變化是不同的

賦值,只是建立一個變數,該變數指向原來記憶體位址(對於賦值,其記憶體位址相同),如:

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}  n2 = n1

 

淺拷貝(只是拷貝了最外面的一層)

import copy  n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}  n3 = copy.copy(n1)

 

 

 深拷貝在記憶體中將所有的資料重新建立一份(排除最後一層,即:python內部對字串和數位最佳化)(拷貝全部,除了最底層)

import copy  n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}  n3 = copy.copy(n1)

 

 8、函數

(函數式:將某功能代碼封裝到函數中,日後便無需重複編寫,僅調用函數即可)

定義和使用:

def 函數名(參數):      ...    函數體    ...    傳回值

 特點

* def:  表示函數的關鍵字

* 函數名:根據函數名調用函數

* 參數: 為函數提供資料

* 函數體:函數中進行一系列的邏輯運算

* 傳回值: 函數執行完畢後,可以給調用者返回一個值,遇到傳回值時下面的程式不執行

參數(形式參數x和實際參數(具體的數))

#發送郵件執行個體
def email():  import smtplib  from email.mime.text import MIMEText  from email.utils import formataddr   msg = MIMEText(‘郵件內容‘, ‘plain‘, ‘utf-8‘)  msg[‘From‘] = formataddr(["武沛齊",‘[email protected]‘])  msg[‘To‘] = formataddr(["走人",‘[email protected]‘])  msg[‘Subject‘] = "主題"   server = smtplib.SMTP("smtp.126.com", 25)  server.login("[email protected]", "郵箱密碼")  server.sendmail(‘[email protected]‘, [‘[email protected]‘,], msg.as_string())  server.quit()
email()

 傳入參數的順序

def  name(k1,k2,k3,k4):

  name(1,2,3,4)       形參,實參(預設,按照順序)      一 一對應的關係   k1-1, k2-2, k3-3, k4-4

def name (k1, k2, k3, k4)

  name(k1=2,k2=1,k3=4,k4=3)     指定形參傳入實參,可以不按照順序   也可以指定

預設參數

def a(p,name="盧曉軍"):       #假如函數中既有有預設值的參數,又有沒有預設值的參數,一定要把沒有預設值的參數放到前面        b=name + "開車去新疆"    return ba()print(a())           # a裡面不傳參數的話預設name="盧曉軍"盧曉軍開車去新疆

 動態參數(一)

def a(*b):        print(b)a(11,22,33,)(11,22,33)         #傳入*b直接把傳入的轉化為元祖

 動態參數(二)

def  a(**b):    print(b)a(k1=123,k2=456){‘k2‘: 456, ‘k1‘: 123}  #傳入**b直接把傳入的轉化為字典

 動態參數結合(一和二)

def  a(p,*b,**c):    print(p)    print(b)    print(c)a(11,22,33,k1=123,k2=456) 11
(22, 33){‘k1‘: 123, ‘k2‘: 456}

 參數的一般寫法:   *args      **kwargs


def a(*b): print(b)li=[11,22,33]a(li)([11, 22, 33],)    #把li當成一個元素進行迴圈
列表def  a(*b):    print(b)li=[11,22,33]a(*li)(11, 22, 33)      # *li:迴圈li裡面的每一個元素
字典def  a(*b):    print(b)li={"k1":"v1","k2":"v2"}a(li)a(*li)({‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘},)(‘k1‘, ‘k2‘)

 

字典(二)def  a(**b):    print(b)li={"k1":"v1","k2":"v2"}a(k1=li)a(**li){‘k1‘: {‘k2‘: ‘v2‘, ‘k1‘: ‘v1‘}}{‘k2‘: ‘v2‘, ‘k1‘: ‘v1‘}

 9、全域變數,局部變數(全域變數都大寫,局部變數都小寫)

a=456       #這裡a是全域變數
def dict(): a=123    #這裡的a是局部變數  下面的print(a)不能執行 print(a)  print(a)dict()

修改全域變數用global  +全域變數

a=123def dict():    global a    a=456dict()def tim():   print(a)tim()456

 練習題

1、簡述普通參數、指定參數、預設參數、動態參數的區別

   普通參數就是使用者輸入的元素按照順序一一對應輸入

  指定參數就是使用者可以指定某一元素傳入某一參數中,可以不按順序

  預設參數就是提前給參數指定一個數值,如果使用者沒有輸入數值。那麼就預設指定的數值是參數

  動態參數就是可以接收使用者輸入的多個元素,元祖,列表通常用*args表示,字典通常用*kwargs

2、寫函數,計算傳入字串中【數字】、【字母】、【空格] 以及 【其他】的個數

def m(p):    a=0    b=0    c=0    for i in p:        if i.isdigit():            a=a+1    for i in p:        if i.isalpha():            b=b+1    for i in p:        if i.isspace():            c=c+1    d=len(p)-(a+b+c)    return a,b,c,dq=m(p)print(q)

3、寫函數,判斷使用者傳入的對象(字串、列表、元組)長度是否大於5。

def z(p):    if len(p)>5:        return True    else:        return Falsea =z(p)print(a)

 4、寫函數,檢查使用者傳入的對象(字串、列表、元組)的每一個元素是否含有空格。

def m(p):    for i in p:        if i.isspace():            return True        else:            return Falsez=m(p)print(z)

5、寫函數,檢查傳入列表的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者。

def z(p):    if len(p)>2:        s=p[0:2]        return s    else:        return Falsem=z(p)print(m)

 6、寫函數,檢查擷取傳入列表或元組對象的所有奇數位索引對應的元素,並將其作為新列表返回給調用者。

def z(p):    d=[]    for i in range(len(p)):        if i%2==1:            d.append(p[i])    return dm=z(p)print(m)

 7、寫函數,檢查傳入字典的每一個value的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者

def z(p):    for i in p.values():        if len(i)>2:            m=i[0:2]    return mc=z(p)print(c)

 

python基礎set

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.