1. 程式人生 > >Python-字典、集合、字符編碼、文件操作整理-Day3

Python-字典、集合、字符編碼、文件操作整理-Day3

兩個 fas cpp pop 聲明 error: iterable ble 解釋

1、字典

1.1、為什麽有字典:

有個需求,存所有人的信息 這時候列表就不能輕易的表示完全
names = [‘stone‘,‘liang‘]

1.2、元組:

  
定義符號()
t = (1,2,3)
tuple 是元組的意思
列表與元組不一樣的地方是它 元組不可以修改
元組其實跟列表差不多,也是存一組數,只不是它一旦創建,便不能再修改,所以又叫只讀列表

語法  
names = ("alex","jack","eric")  

它只有2個方法,一個是count,一個是index,完畢。

1.3、列表:

list = [1,2,3,4]
用列表去查復雜的信息和取數據就很麻煩
利用字典:存儲更復雜的數據

1.4、定義字典:

定義:{key1:value1,key2:value2},key-value結構,key必須可hash
特性:

  1. 可存放多個值
  2. 可修改指定key對應的值,可變
  3. 無序

    dic = {‘key‘:‘value‘,‘age‘:‘18‘}
    字典的元素是由key:value 組成的
    dic= {} --> dict() --> init()

1.5、小技巧:

按ctrl 直接到對應函數的操作成員列表內

>>> dic4 = dict(name=‘stone‘,age = 18)
>>> print(dic4)
{‘age‘: 18, ‘name‘: ‘stone‘}
>>> dic5 = dict({‘name‘:‘stone‘,‘age‘:18})
>>> print dic5
  File "<stdin>", line 1
    print dic5
             ^
SyntaxError: Missing parentheses in call to ‘print‘
>>> print(dic5)
{‘age‘: 18, ‘name‘: ‘stone‘}

2、字典的基本操作:

2.1、查詢

dic[‘key‘]
dic[‘name‘]
直接在字典裏面找KEY 取到value
列表的查詢:
print(dic["namee"])
沒有的話會直接報錯
但是字典get不會報錯
print(dic.get(‘naness‘))
輸出none

2.2、增加

字典中添加是無序的添加
dic[‘gender‘]=‘female‘
列表是有序的

2.3、改

dic[‘name‘] = ‘stone‘
改的是value

2.4、刪除

del 萬能的
del dic[‘name‘]
字典裏面怎麽定義的key 調用的時候就是那麽寫

2.5、復制:copy 淺copy

dic1 = dic.copy()
print(dic1)

2.6、深入 copy

import copy
dic3 = copy.deepcopy(dic)
copy.copy是淺copy

2.7、快速生成字典fromkeys

dic= {‘name‘:‘stone‘,‘age‘:18}
data = dic.fromkeys([1,2,3])
print(date)
輸出:
{1: None, 2: None, 3: None}
生成的字典跟聲明的字典dic沒有關系

2.8、items

print(dic.items())
for i in dic.items():
print(i)

2.9、key value形式

keys將字典中所有的key取出  
將所有的keys以列表的形式顯示出來  
for i in dic.keys():
    print(‘keys is %s,value is %s‘ %(i,dic[i]))
以列表和元組的形式顯示出來  

2.10、刪除pop()

dic.pop(keys)
註意是只能是填寫keys
pop(keys)必須存在才能刪除

2.11、隨機刪除popitem()

隨機刪除key value
這個函數不需要函數隨機刪除

2.12、setdefault

dic.setdefault(‘gender‘,[]).append(‘mail‘) #dic[‘gender‘]=[]
或者是
dic[‘gender‘].appemd(‘female‘)

2.13、更新update

方法一:
dic1={‘gender‘:‘male‘,‘name‘:‘lhf‘}
dic.update(dic1)
print(dic)
方法二:
可以根據key進行更新
dic.update(name=‘stone‘,gender=‘male‘)
print(dic)

2.14、values取所有的值

for i in dic.values(dic1)
    print(i)

3、字典key的定義規則:

3.1、可變的原理:

通過id()進行內存調用查看是否是一個內存空間
字符串和數字是不可變的
列表:是可變的類型 是指列表裏面包含的元素可變

3.2、key的定義規則

  1. 必須是不可變的,不可變的類型:數字,字符串,元組
  2. 通過內置方法hash 判斷一個數據類型是否可變

    hash(‘sdfas‘)
    -41789881
    hash[‘s‘] #hash 列表
    Traceback (most recent call last):
    File "

  3. 字典當中的key是唯一的:不能是重復的

判斷一個字典裏有沒有這個值

菜單思路:
首先一個死循環

數據類型的小結分類說明

4、集合

4.1、定義

由不同元素組成的集合,集合中是一組無序排列的可hash值,可以作為字典的key

4.1.1、集合的創建

{1,2,3,1}
或
定義可變集合set
>>> set_test=set(‘hello‘)
>>> set_test
{‘l‘, ‘o‘, ‘e‘, ‘h‘}
改為不可變集合frozenset
>>> f_set_test=frozenset(set_test)
>>> f_set_test
frozenset({‘l‘, ‘e‘, ‘h‘, ‘o‘})

4.2、特性

  1. 集合的目的是將不同的值存放到一起,不同的集合間用來做關系運算,無需糾結於集合中單個值
  2. 元素唯一:

    例子:
    s1= {‘a‘,1,2,‘b‘,‘c‘,‘c‘}
    print(s1)
    不會有相同的元素

4.3、集合的關系運算

in
not in
==
!=
<,<=
>,>=
|,|=:合集
&.&=:交集
-,-=:差集
^,^=:對稱差分

4.3.1、交集

查看不同集合中共有的元素:s1&s2(集合的內置方法)== intersection()

4.3.2、並集

s1|s2 == union()

4.3.3、差集

s1-s2 == 

4.3.4、對稱差集

把多個集合的交集去除s1^s2

4.3.5、子集

s2 <= s1 s2是s1的子集

4.3.6、父集

s2 => s1 s1是s2的子集

4.4、集合其他的內置方法

4.4.1、update

s1.update(‘2‘)
s1.update((1,2,3,4))
s2 = {‘h‘,‘2‘,‘1‘}
s1.update(s2)
s1.update(‘hello‘)

4.4.2、增加

s1.add(‘hello‘)
print(s1)

4.4.3、隨機刪除pop()

4.4.4、指定刪除

remove()
s1.remove(‘a‘)
s1.remove(‘w‘)
print(s1)
以上用remove()沒有元素會報錯:
不報錯刪除:
s1:discard(‘w‘)
用以上的會默認輸出none 不會拋出異常

4.4.5、拷貝:

copy 跟字典是一樣的
difference_update s1 =s1 -s2

4.5、集合工廠函數

s = set([3,5,9,10])      #創建一個數值集合    
t = set("Hello")         #創建一個唯一字符的集合  
a = t | s          # t 和 s的並集   
b = t & s          # t 和 s的交集   
c = t – s          # 求差集(項在t中,但不在s中)   
d = t ^ s          # 對稱差集(項在t或s中,但不會同時出現在二者中)  
    
基本操作:    
t.add(‘x‘)            # 添加一項   
s.update([10,37,42])  # 在s中添加多項   
使用remove()可以刪除一項:  
t.remove(‘H‘)    
len(s)  
set 的長度  
x in s  
測試 x 是否是 s 的成員   
x not in s  
測試 x 是否不是 s 的成員  
  
s.issubset(t)  
s <= t  
測試是否 s 中的每一個元素都在 t 中  
  
s.issuperset(t)  
s >= t  
測試是否 t 中的每一個元素都在 s 中  
  
s.union(t)  
s | t  
返回一個新的 set 包含 s 和 t 中的每一個元素  
  
s.intersection(t)  
s & t  
返回一個新的 set 包含 s 和 t 中的公共元素  
  
s.difference(t)  
s - t  
返回一個新的 set 包含 s 中有但是 t 中沒有的元素  
  
s.symmetric_difference(t)  
s ^ t  
返回一個新的 set 包含 s 和 t 中不重復的元素  
  
s.copy()  
返回 set “s”的一個淺復制

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
    """
    相當於s1-s2
    
    Return the difference of two or more sets as a new set.
    
    (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. """
    pass

def discard(self, *args, **kwargs): # real signature unknown
    """
    與remove功能相同,刪除元素不存在時不會拋出異常
    
    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
    """
    相當於s1&s2
    
    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. """
    pass

def isdisjoint(self, *args, **kwargs): # real signature unknown
    """ Return True if two sets have a null intersection. """
    pass

def issubset(self, *args, **kwargs): # real signature unknown
    """ 
    相當於s1<=s2
    
    Report whether another set contains this set. """
    pass

def issuperset(self, *args, **kwargs): # real signature unknown
    """
    相當於s1>=s2
    
     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
    """
    相當於s1^s2
    
    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. """
    pass

def union(self, *args, **kwargs): # real signature unknown
    """
    相當於s1|s2
    
    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

5、字符編碼

5.1、 什麽是字符編碼

計算機要想工作必須通電,也就是說‘電’驅使計算機幹活,而‘電’的特性,就是高低電壓(高低壓即二進制數1,低電壓即二進制數0),也就是說計算機只認識數字

編程的目的是讓計算機幹活,而編程的結果說白了只是一堆字符,也就是說我們編程最終要實現的是:一堆字符驅動計算機幹活

所以必須經過一個過程:

  字符串--------(翻譯過程)------->數字

這個過程實際就是一個字符如何對應一個特定數字的標準,這個標準稱之為字符編碼

1.  內存固定使用unicode,硬盤的編碼(可以修改的軟件編碼)
2.  使用什麽編碼存儲,就用什麽編碼讀取
3.  程序運行分兩個階段,1.從硬盤讀到內存 2. python 解釋器運行已經讀到內存的代碼
4.  針對一個文件來說,python 與nodpad++ 區別是多了第二個步驟
5.  coding 指定字符編碼 是在告訴解釋器 使用什麽字符編碼讀取文件
  

6、文件處理

6.1、文件處理流程

1. 打開文件,得到文件句柄並賦值給一個變量
2. 通過句柄對文件進行操作
3. 關閉文件

6.2、文件操作基本流程

f = open(‘a.txt‘) #打開文件
first_line = f.readline()  #讀取文件第一行
print(‘first line:‘,first_line) #打印第一行
print(‘華麗分隔線‘.center(50,‘-‘))
data = f.read()   # 讀取剩下的所有內容,文件大時不要用
print(data)       #打印讀取內容
f.close()         #關閉文件

6.3、詳細操作

data = open("test").read()
read() 將文件內容全部讀取出來
打開文件的時候應該先定義變量:
f = open(test)
print(f.readline())
strip() 會把整行的開頭末尾的空格和換行去除
f.readline()一行一行讀,從上一行
f.readlines() 會將文件內容輸出 以列表展示

6.4、實現循環讀取文件部分內容:

方法一:不要用readlines()

for index,line in enumerate(f.readlines()):
    if index <5:
        print(line.strip())
    else:
        break

#####enumerate 只能用於列表

方法二:

for i in range(5):
    print(f.readline().strip())

方法三:

for line in f:
    print(line.strip())
一行行處理

line_nu = 0
for line in f:
    if line_nu < 5:
        print(line.strip())
        line_nu +=1
    else:
        break

6.5 文件操作模式

文件句柄 = open(‘文件路徑‘, ‘模式‘)

打開文件時,需要指定文件路徑和以何等方式打開文件,打開後,即可獲取該文件句柄,日後通過此文件句柄對該文件操作。

打開文件的模式有:

r ,只讀模式【默認模式,文件必須存在,不存在則拋出異常】
w,只寫模式【不可讀;不存在則創建;存在則清空內容】
x, 只寫模式【不可讀;不存在則創建,存在則報錯】
a, 追加模式【可讀;   不存在則創建;存在則只追加內容】

"+" 表示可以同時讀寫某個文件

r+, 讀寫【可讀,可寫】
w+,寫讀【可讀,可寫】
x+ ,寫讀【可讀,可寫】
a+, 寫讀【可讀,可寫】

"b"表示以字節的方式操作

rb  或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b

註:以b方式打開時,讀取到的內容是字節類型,寫入時也需要提供字節類型,不能指定編碼

6.6 文件操作示例

6.6.1 寫 "w"

f = open("myfile","w")
f.write("我愛北京天安門\n")
f.write("我愛燙頭\n")
f.close()
以上輸入會以一行的形式顯示。換行添加“\n”

註意:w模式會將原文件內容清空並寫入新數據!!!
w:創建文件並清空該文件內容
###沒有聲明模式:默認模式是讀模式 r

6.6.2、a:追加

f = open("myfile",‘a‘)
f.write("我愛\n")
f.close
追加文件內容結尾

6.6.3、混合模式:可讀可寫

讀寫:r+
寫讀:w+
追加讀:a+
insert的內容會 追加到最後面

6.6.4、closed判斷文件是否關閉

print(f.closed)

6.6.5、打印文件的字符集編碼

print(f.encoding)

6.6.6、操作系統打開文件的索引

print(f.fileno())

6.6.7、強制將內存內容刷到磁盤

f.flush()
實時的刷新內存內容到磁盤

flush原理:

文件操作是通過軟件將文件從硬盤讀到內存寫入文件的操作也都是存入內存緩沖區buffer  
(內存速度快於硬盤,如果寫入文件的數據都從內存刷到硬盤,
內存與硬盤的速度延遲會被無限放大,效率變低,
所以要刷到硬盤的數據我們統一往內存的一小  塊空間即buffer中放,
一段時間後操作系統會將buffer中數據一次  性刷到硬盤)  
flush即,強制將寫入的數據刷到硬盤  

滾動條:

import sys,time

for i in  range(10):
    sys.stdout.write(‘#‘)
    sys.stdout.flush()
    time.sleep(0.2)

6.6.8、判斷是否是終端文件,不可讀

f.isatty()

6.6.9、打印文件名

f.name :打印文件名

6.6.10、按字符尋找

f.seek()#尋找
f.seek(10)
print(f.readline())
找到什麽位置(以字符為n)

6.6.11、告訴當前光標位置

print(f.tell())
print(f.readline())

6.6.12、f.truncate()從光標位置截斷並移除後面的所有內容

f.truncate() #截斷 
註意需要打開文件執行
對於文本的截斷沒有什麽卵用
對於二進制文件進行截斷 斷點續傳

6.6.13、f.writelines()

data = ["stone\n","liang"]
將列表裏面的值 追加到內容前

6.7、執行腳本傳入參數

Python有大量的模塊,從而使得開發Python程序非常簡潔。類庫有包括三中:
Python內部提供的模塊
業內開源的模塊
程序員自己開發的模塊
Python內部提供一個 sys 的模塊,其中的 sys.argv 用來捕獲執行執行python腳本時傳入的參數

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import sys
 
print sys.argv

Python-字典、集合、字符編碼、文件操作整理-Day3