python基礎2

SDYTXM發表於2017-11-08

1.列表元組

列表是我們最以後最常用的資料型別之一,通過列表可以對資料實現最方便的儲存、修改等操作.

定義列表:

1 # yu
2 
3 names=["啦啦","嘿嘿",`魚魚`]

我們通過列表下標進行資料的提取:

1 # yu
2 names=["啦啦","嘿嘿",`魚魚`]
3 print(names)
4 print(names[0])#第一個資料從0開始
5 print(names[-1])#倒過來取值

切片:

1 # yu
2 names=["lala","heihei",`yuyu`,`hehe`,`haha`]
3 print(names[1:3])#取下標1 ,不包含下標3 [`heihei`, `yuyu`]
4 print(names[1:-1])#取下標1至-1的值,不包括-1
5 print(names[:3])#如果是從頭開始取,0可以忽略
6 print(names[3:])#取到最後一個值
7 print(names[3:-1])#取不到最後一個值
8 print(names[0::2])#後面的2是代表,每隔一個元素,就取一個

View Code

追加:

1 # yu
2 names=["lala","heihei",`yuyu`,`hehe`,`haha`]
3 names.append("嘻嘻")
4 print(names)
5 #結果[`lala`, `heihei`, `yuyu`, `hehe`, `haha`, `嘻嘻`]

View Code

插入:

1 # yu
2 names=["lala","heihei",`yuyu`,`hehe`,`haha`]
3 names.insert(2,`從2插入`)
4 print(names)
5 #結果[`lala`, `heihei`, `從2插入`, `yuyu`, `hehe`, `haha`]

View Code

修改:

1 # yu
2 names=["lala","heihei",`yuyu`,`hehe`,`haha`]
3 names[1]=`修改下標為1`
4 print(names)
5 #結果[`lala`, `修改下標為1`, `從2插入`, `yuyu`, `hehe`, `haha`]

View Code

刪除:

1 names=["lala","heihei",`yuyu`,`hehe`,`haha`]
2 #names.clear()#清空列表
3 print(names)#返回[]
4 #del names[1]#刪除指定下標的值
5 print(names)#[`lala`, `yuyu`, `hehe`, `haha`
6 #names.remove("yuyu")#刪除指定的值
7 print(names)
8 names.pop()#預設刪最後一個,也可以加入你祥刪除的下標
9 print(names)

View Code

擴充套件:

1 # yu
2 names=["lala","heihei",`yuyu`,`hehe`,`haha`]
3 b=[1,2,3]
4 names.extend(b)
5 print(names)#[`lala`, `heihei`, `yuyu`, `hehe`, `haha`, 1, 2, 3]

View Code

拷貝(淺拷貝與深拷貝的區別):

1 names=["Young","Jon",["Tom","Jerry"],`Jems`,`Sunny`]
2 names2 = names.copy()
3 names[1]="淺copy"
4 names[2][0]="深copy"
5 print(`name1:`,names)
6 print(`name2:`,names2)
7 #結果
8 #name1: [`Young`, `淺copy`, [`深copy`, `Jerry`], `Jems`, `Sunny`]
9 #name2: [`Young`, `Jon`, [`深copy`, `Jerry`], `Jems`, `Sunny`]

View Code

統計:

1 # yu
2 names=["lala","heihei",`yuyu`,`hehe`,`haha`,`haha`]
3 print(names.count(`haha`))#結果2

View Code

排序:

1 # yu
2 names=["1lala","3heihei",`5yuyu`,`4hehe`,`2haha`,`1haha`]
3 names.sort()
4 print(names)

View Code

反轉:

1 names=["1lala","2heihei",`3yuyu`,`4hehe`,`5haha`,`6haha`]
2 names.reverse()
3 print(names)
4 #結果[`6haha`, `5haha`, `4hehe`, `3yuyu`, `2heihei`, `1lala`]

View Code

獲取下標:

1 # yu
2 names=["0lala","1heihei",`2yuyu`,`3hehe`,`4haha`,`5haha`]
3 print(names.index("2yuyu"))#2

View Code

元組

元組其實跟列表差不多,也是存一組數,只不是它一旦建立,便不能再修改,所以又叫只讀列表

定義:

names=("lala","heihei",`yuyu`,`hehe`,`haha`,`haha`)

它只有2個方法,一個是count,一個是index.

 

2.字串操作

特性;不可修改.

# yu
name=`young`
 #首字母大寫
print(name.capitalize() )
# name.casefold()   大寫全部變小寫
print(name.center(50,"-") ) #輸出----------------------young-----------------------
# name.count(`lex`) 統計 lex出現次數
# name.encode()  將字串編碼成bytes格式
# name.endswith("g")  判斷字串是否以g結尾
#  "Young	Y".expandtabs(10) 輸出`Young      Y`, 將	轉換成多長的空格
print(name.find(`o`))  #查詢A,找到返回其索引, 找不到返回-1
 1 #format
 2 cata = "my name is {}, and age is {}"
 3 print(cata.format("young",23))#結果my name is young, and age is 23
 4 cata = "my name is {}, and age is {}"
 5 print(cata.format("23",`young`))#my name is 23, and age is young
 6 cata = "my name is {name}, and age is {age}"
 7 print(cata.format(age=23,name=`young`))
 8 
 9 #format_map
10 cata = "my name is {name}, and age is {age}"
11 print(cata.format_map({`name`:`young`,`age`:23}))

View Code

cata = "my name is {name}, and age is {age}"
print(cata.index(`a`))
print(`9aA`.isalnum() )
print(`9`.isdigit() )#是否整數)
name=`Hello`
print(name.isnumeric  )
# name.isprintable
# name.isspace
# name.istitle
# name.isupper
print("|".join([`lala`,`hihi`,`wow`]))

View Code

#maketrans
intab = "aeiou"  #This is the string having actual characters.
outtab = "12345" #This is the string having corresponding mapping character
trantab = str.maketrans(intab, outtab)
print(trantab)
str = "this is string example....wow!!!"
print(str.translate(trantab))
#     `th3s 3s str3ng 2x1mpl2....w4w!!!`

View Code

1 print(cata.partition(`is`))#(`my name `, `is`, ` {name}, and age is {age}`)
2 print(cata.swapcase())#大小寫互換
3 print(cata.zfill(40))
4 n=`hello world`
5 print(n.ljust(40, "-"))
6 print(n.rjust(40, "-"))
7 b="ddefdsdff_哈哈" 
8 b.isidentifier() #檢測一段字串可否被當作標誌符,即是否符合變數命名規則

View Code

 3.字典操作

字典一種key – value 的資料型別.

定義:

info = {
    "1":"嘻嘻",
    "2":"哈哈",
    "3":"呵呵",
    "4":"嘿嘿"
}

字典的特性:

  • dict是無序的
  • key必須是唯一的

增刪改查:

#
info["5"]="哇哇"
 #
 info["1"]="麼麼"
 print(info)
#
info.pop("1")
#del info["1"]
#info.popitem()#隨機刪除
#
print("3" in info)
print(info["3"])
print(info.get("2"))
print(info)

View Code

其他方法:

print(info.keys())
print(info.values())

info2 = {
    "5":`啦啦`,
    `6`:`哼哼`
}
info.update(info2)
print(info)
print(info.setdefault("1","大少"))

print(info.items())

View Code

迴圈dict:

#兩種方法:
for key in info:
    print(key,info[key])

for k,v in info.items():
    print(k,v)

View Code

三級選單:

  1. 列印省、市、縣三級選單
  2. 可返回上一級
  3. 可隨時退出程式
data = {
    `黑龍江`:{
        "哈爾濱":{
            "南崗":["凱德","許樂會所"],
            "松北":["君慕稀","大保健"]
        },
        "牡丹江":{
            "鏡泊湖":["大山","河流"],
            "好地方":{"優美","地靈"},
            "小城":{"故事","美好"},
        },
        "海淀":{},
    },
    `山東`:{
        "德州":{},
        "青島":{},
        "濟南":{}
    },
    `廣東`:{
        "東莞":{},
        "常熟":{},
        "佛山":{},
    },
}

exit_flag = False
while not exit_flag:
    for i in data:
        print(i)
        choice = input(">>選擇進入1")
        if choice  in data:
            while not exit_flag:
                for i2 in data[choice]:
                    print("	",i2);
                choice2 = input(">>選擇進入2")
                if choice2 in data[choice]:
                    while not exit_flag:
                        for i3 in data[choice][choice2]:
                            print("		", i3);
                        choice3 = input(">>選擇進入3")
                        if choice3 in data[choice][choice2]:
                            for i4 in data[choice][choice2][choice3]:
                                print("		", i4);
                            choice4 =input("最後一次,按b返回")
                            if choice4 =="b":
                                pass
                            elif choice4 =="q":
                                 exit_flag=True;
                        if choice3 == "b":
                             break
                        elif choice3 == "q":
                            exit_flag = True;
                if choice2 == "b":
                    break
                elif choice2 == "q":
                    exit_flag = True;

View Code

4.集合操作

集合是一個無序的,不重複的資料組合,它的主要作用如下:

  • 去重,把一個列表變成集合,就自動去重了
  • 關係測試,測試兩組資料之前的交集、差集、並集等關係

常用操作:

#定義一個集合
list1=[1,23,4,5,6,0]
list1 =set(list1)
list2=set([1,2,7,8,9,0])
```
print (list1)
print(list2)

#交集
print(list1.intersection(list2))
print(list1 & list2)
#並集
print(list1.union(list2))
print(list1 | list2)
#差集
print(list1.difference(list2))
print(list1 - list2)

#子集
list3 = set([1,2,3,4])
list4 = set([1,2])
list5 = set([0,9])
print(list4.issubset(list3))
print(list3.issuperset(list4))
#對稱差集
print(list1.symmetric_difference(list2))


print("-----------------------")
print(list3.isdisjoint(list5))#看有沒有交集,並返回true or false;

```
#新增,沒有插入
list1.add(12)
print(list1)
#
print(list1.pop())
print(list1.pop())
print(list1)
list1.discard(23)
print(list1)

View Code

5.檔案操作

對檔案操作流程

  1. 開啟檔案,得到檔案控制程式碼並賦值給一個變數
  2. 通過控制程式碼對檔案進行操作
  3. 關閉檔案 

檔案text:

晚風輕拂著澎湖灣
白浪逐沙灘
沒有椰林醉斜陽
只是一片海藍藍
坐在門前的矮牆上一遍遍幻想
也是黃昏的沙灘上有著腳印兩對半
那是外婆拄著杖將我手輕輕挽
踩著薄暮走向餘暉暖暖的澎湖灣
一個腳印是笑語一串消磨許多時光
直到夜色吞沒我倆在回家的路上
澎湖灣澎湖灣外婆的澎湖灣
有我許多的童年幻想
陽光沙灘海浪仙人掌
還有一位老船長

View Code

基本操作:

1 f = open("外婆的澎湖灣",encoding=`utf-8`)#檔案控制程式碼,
2 # f.write("hello world
".encode())
3 f1 = f.readline()
4 print(`first line:`,f1)
5 print(`我是分隔線`.center(50,`-`))
6 data = f.read()# 讀取剩下的所有內容,檔案大時不要用
7 print(data) #列印檔案
8 f.close()

View Code

開啟檔案的模式有:

  • r,只讀模式(預設)。
  • w,只寫模式。【不可讀;不存在則建立;存在則刪除內容;】
  • a,追加模式。【可讀;   不存在則建立;存在則只追加內容;】

“+” 表示可以同時讀寫某個檔案

  • r+,可讀寫檔案。【可讀;可寫;可追加】
  • w+,寫讀
  • a+,同a

“U”表示在讀取時,可以將

自動轉換成
(與 r 或 r+ 模式同使用)

  • rU
  • r+U

“b”表示處理二進位制檔案(如:FTP傳送上傳ISO映象檔案,linux可忽略,windows處理二進位制檔案時需標註)

  • rb
  • wb
  • ab

with語句

為了避免開啟檔案後忘記關閉,可以通過管理上下文,即:

1 with open(`外婆的澎湖灣`,`r`) as f:
2      
3     ...

如此方式,當with程式碼塊執行完畢時,內部會自動關閉並釋放檔案資源。

在Python 2.7 後,with又支援同時對多個檔案的上下文進行管理,即:

1 with open(`log1`) as obj1, open(`log2`) as obj2:
2     pass

6.字元的編碼與轉碼

參考文章:

http://www.cnblogs.com/yuanchenqi/articles/5956943.html

需知:

1.在python2預設編碼是ASCII, python3裡預設是unicode

2.unicode 分為 utf-32(佔4個位元組),utf-16(佔兩個位元組),utf-8(佔1-4個位元組), so utf-16就是現在最常用的unicode版本, 不過在檔案裡存的還是utf-8,因為utf8省空間

3.在py3中encode,在轉碼的同時還會把string 變成bytes型別,decode在解碼的同時還會把bytes變回string

python3中:

 1 import sys
 2 print(sys.getdefaultencoding())
 3 s = "你好"
 4 
 5 s_gbk = s.encode("gbk")
 6 
 7 print(s_gbk)#gbk
 8 
 9 print(s.encode())#utf8
10 
11 gbk_to_utf8 = s_gbk.decode("gbk").encode("utf-8")
12 print(gbk_to_utf8)

View Code

 


相關文章