python 筆記2

1、 set集合

set,無序,不重複序列

建立列表php

#建立set集合的幾種方式
se = {123,456}
s = set()
s1 = list(se)
print(set([11,22,33,22]))
print(type(se))

找出s1中存在,s2中不存在的值python

>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s1.difference(s2)
{11}

 s1於s2的對稱差集express

s1 = {11,22,33}
s2 = {11,22,44}
s3 = s1.symmetric_difference(s2)
print(s3)

輸出
{33, 44}

移除指定元素函數

s1 = {11,22,33}
#移除指定元素,元素不存在時不報錯
s1.discard(11)
print(s1)

輸出
{33, 22}

取set中交集ui

s1 = {11,22,33}
s2 = {11,22,44}
print(s1.intersection(s2))

{11, 22}

批量添加元素this

s1 = {11,22,33}

s3 = [6,23,4]
s1.update(s3)
print(s1)


輸出
{33, 4, 6, 11, 22, 23}

set的詳細方法spa

class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
     
    Build an unordered collection of unique elements.
    """
    def add(self, *args, **kwargs): # real signature unknown
        """
        Add an element to a set,添加元素
         
        This has no effect if the element is already present.
        """
        pass
 
    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. 清除內容"""
        pass
 
    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. 淺拷貝  """
        pass
 
    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set. A中存在,B中不存在,差別比對
         
        (i.e. all elements that are in this set but not the others.)
        """
        pass
 
    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set.  從當前集合中刪除和B中相同的元素"""
        pass
 
    def discard(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set if it is a member.
         
        If the element is not a member, do nothing. 移除指定元素,不存在不保錯
        """
        pass
 
    def intersection(self, *args, **kwargs): # real signature unknown
        """
        Return the intersection of two sets as a new set. 交集
         
        (i.e. all elements that are in both sets.)
        """
        pass
 
    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another.  取交集並更更新到A中 """
        pass
 
    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection.  若是沒有交集,返回True,不然返回False"""
        pass
 
    def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set.  是不是子序列"""
        pass
 
    def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. 是不是父序列"""
        pass
 
    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty. 移除元素
        """
        pass
 
    def remove(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set; it must be a member.
         
        If the element is not a member, raise a KeyError. 移除指定元素,不存在保錯
        """
        pass
 
    def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """
        Return the symmetric difference of two sets as a new set.  對稱差集
         
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass
 
    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. 對稱差集,並更新到a中 """
        pass
 
    def union(self, *args, **kwargs): # real signature unknown
        """
        Return the union of sets as a new set.  並集
         
        (i.e. all elements that are in either set.)
        """
        pass
 
    def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. 更新 """
        pass

2、 python 函數

  • 定義函數
  1. 函數代碼塊以 def 關鍵詞開頭,後接函數標識符名稱和圓括號()
  2. 任何傳入參數和自變量必須放在圓括號中間。圓括號之間能夠用於定義參數。
  3. 函數的第一行語句能夠選擇性地使用文檔字符串—用於存放函數說明。
  4. 函數內容以冒號起始,而且縮進。
  5. return [表達式] 結束函數,選擇性地返回一個值給調用方。不帶表達式的return至關於返回 None。
  • 語法定義及調用函數
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 定義函數
def printme( str ):
   "打印任何傳入的字符串"
   print str;
   return;
 
# 調用函數
printme("我要調用用戶自定義函數!");
printme("再次調用同一函數");
  • 函數返回值
  • 在函數中,一旦執行return,函數體就會中止向下執行
#!/usr/bin/python3

def f1():
    print(1234)
    return '12'
    print(496)

f1()

輸出:
1234
  • 函數傳參
#!/usr/bin/python3

#函數傳入參數

def send(aa,bb):
    print(aa,bb)

send('11','22')

#輸出
11,22

#傳入默認參數,默認參數必須在傳參列表的末尾
def send(aa,bb='OK'):
    print(aa,bb)
send('11')

#輸出
11,OK
  • 函數動態參數1
#* 能夠傳入N個參數,默認將參數寫到元組裏面
def f1(*args):
    print(args)
li = [22,3,5,7]
#傳參時帶*和不帶是不同的
f1(li)          #將整個列表都傳入
f1(*li)         #將列表轉換爲元組,至關於作了一個for循環
f1('11',22,33,44)

輸出
([22, 3, 5, 7],)
(22, 3, 5, 7)
('11', 22, 33, 44)
  • 函數動態參數2
#當參數前面是2*號是,傳入參數是須要傳入一個key,一個value,默認把參數放到字典中
def f1(**args):
    print(args)

dic = {'k1':'v1','k2':'v2'}
# 傳入時傳入兩個*,會將字典原本來本寫進去,兩個鍵值對
f1(**dic)
#這樣會變成一個鍵值對
f1(v1=dic)
f1(key='vv',k=11)

輸入
{'k1': 'v1', 'k2': 'v2'}
{'v1': {'k1': 'v1', 'k2': 'v2'}}
{'key': 'vv', 'k': 11}

-----------------------------------------------------------------------
#可傳入任何參數
def f1(*args,**kwargs):
    print(args)
    print(kwargs)

dic = {'k1':'v1','k2':'v2'}
f1(11,22,33,**dic)
f1(11,22,33,k1='v1',k2='v2')
#注意不能這麼寫
#f1(11,22,33,k1='v1',k2='v2',**dic)

輸出
(11, 22, 33)
{'k1': 'v1', 'k2': 'v2'}
(11, 22, 33)
{'k1': 'v1', 'k2': 'v2'}

3、 全局變量

  • 規則是定義全局變量時須要將變量名大寫
  • 沒寫到函數裏面的都是全局變量,在全部做用域裏面都能讀;指針

  • 函數內修改全局變量時須要在函數內加上關鍵字global,實例以下:code

  • 特殊:當全局變量爲字典列表時,可修改,但不可從新賦值
#!/usr/bin/python3

NAME = 6
#修改全局變量時加上global
def f1():
    global NAME
    print(NAME)
    NAME = 2
    print(NAME)

f1()

輸入:
6
2



——————————————————————————————-
#若是不加global,就會報下面的錯誤

X = 6

def f1():
    print(X)
    x = 2
    print(X)

f1()

輸入:
UnboundLocalError: local variable 'X' referenced before assignment

4、三元運算(if-else簡寫)

# 這樣寫須要4行完成
if 1 == 1:
    name = 'aa'
else:
    name = 'bb'

# print(name)

# 這樣只要一行就好了,若是1=1 則name='aa'不然name = 'bb'
name = 'aa' if 1 == 1 else 'bb'
print(name)

5、Lambda 表達式

  • lambda 語法:lambda arg1, arg2, ....: expression
  • lambda中arg一、arg2等於函數式的參數,之後你能夠在expression中使用這些參數。注意!lambda是運算式,不是陳述句,你在:之後的也必須是運算式,lambda中也不能有區塊,這表示一些小的運算任務你可使用lambda,而較複雜的邏輯你可使用def來定義。
#這兩種寫法徹底是同樣的

def f1(a1,b1):
    return a1+b1

f2 = lambda a1,b1: a1+b1

print(f1(2,3))
print(f2(5,1))

6、 內置函數

  • abs() 取絕對值, abs(-1)
  • all()   當傳參裏全部的布爾值爲真,返回的結果才爲真
  • any()   當傳參裏任何一個的布爾值爲真,返回的結果就爲真
  • ascii()    自動執行對象的__repr__方法
  • bin()     接收一個十進制,將十進制轉換成二進制
  • oct()     接收一個十進制,將十進制轉換成八進制
  • hex()    接收一個十進制,將十進制轉換成十六進制
  • bytes()   將字符串轉換爲字節類型 ,bytes('字節','utf-8')    #python3
  • str()      將字節轉換爲字符串, str(b'\xe9\xa3\x9e',encoding="utf-8")

7、文件操做

  • 打開文件(若是打開文件出現亂碼,多是encoding='' 出現問題,(通常在追加內容是打開方式都用r+)
#!/usr/bin/python3

f = open('db','r')    #已只讀方式打開文件
f = open('db','x')    #文件存在就報錯,文件不存,建立並寫入內容
f = open('db','w')    #只寫,先清空
f = open('db','a')    #追加內容

#若是文件打開是亂碼,可能你保存的時候就是gbk格式的文件,須要進行轉化一下
f = open('db','r', encoding='utf-8')

# 讀寫模式後面加上b就是以二進制的方式讀取文件
f = open('db','rb')

f = open('db','r+')    #可讀可寫,位置指針放在末尾
  • 操做文件
#!/usr/bin/python3

# 二進制和普通讀取方式區別,默認read()無參數,則讀所有
f = open('user_list.txt','rb')
print(f.read(),type(f.read()))
f.close()
print('---'*10)
z = open('user_list.txt','r')
print(z.read(),type(z.read()))
z.close()

#輸出
b'admin|123\nadmin2|123\nadmin3|fsg' <class 'bytes'>
------------------------------
admin|123
admin2|123
admin3|fsg <class 'str'>

# 當文件以二進制方式打開的時候,寫入
f = open('user_list.txt','ab')
f.write(bytes('hello', encoding='utf8'))
f.close()


-------------------------------
#調整讀取位置指針,若是有值會覆蓋掉,讀取位置是以字節的方式讀取的,若是是那個位置是中文,極可能就會出現亂碼
z = open('user_list.txt','r')
z.seek(12)    #跳轉到指定位置
z.tell()    #獲取當前文件指針的位置
z.write()    #寫數據,打開方式有b按字節
z.fileno()
z.flush()   #強制刷新到硬盤上
z.readable()    #判斷內容是否可讀
z.readline()    #僅讀取一行
z.truncate()    #截斷,指針後面內容所有刪除

#for循環文件對象,一行一行的讀取文件
f = open('db','r')
for line in f:
    print(f)
f.close()
  • 關閉文件
# z = open('user_list.txt','r')
# print(z.read(),type(z.read()))
# z.close()     #關閉文件
  • 文件操做 with open()
# 經過with 處理上下文,同時打開兩個文件,在python3中支持

# 將aa文件中前10行,寫入到bb文件中
with open('aa','r') as f, open('bb','w') as f2:

    lines = 0
    for line in f:      #讀一行,寫一行
        lines += 10
        if lines <= 10:
            f2.write(line)
        else:
            break
# 將aa文件中的file改爲files,寫到bb文件中
with open('aa','r') as f, open('bb','w') as f2:
    for line in f:      #讀一行,寫一行
        now_str = line.replace('file','files')
        f2.write(now_str)
相關文章
相關標籤/搜索