1. 程式人生 > 實用技巧 >Python基礎-v1

Python基礎-v1

為什麼要學Python?大一大二學了“線代、概率統計、高數”,如今臨近大三暑假,想通過學習“深度學習”來複習鞏固這些數學知識;然後就是每次開發小專案系統,很痛苦的就是資料來源問題,最有效的一個辦法就是通過爬蟲,而據我瞭解的一般都是通過Python爬取的;還有Python是“膠水語言”,跨平臺,相容性好,學的意義很大。

1 學習資源

訊飛AI大學-Python基礎入門-趙權

廖雪峰Python教程

微軟Python教程-入門

微軟Python教程-進階

微軟Python教程-高階

微軟Python教程原始碼

小甲魚Python教程

2 環境配置

Python官方下載

VSC官方下載

2.1 Anaconda環境配置

Anaconda下載(官方)

Anaconda下載(清華大學映象)

百度百科-Anaconda包管理器

維基百科-Anaconda包管理器

編輯器包括SpyderJupyter,我這裡選擇Jupyter

3 常量變數

變數

i = 666 # 將666賦值給變數
print(i) # 列印變數i
666
i = 888 # 將888重新賦值給變數
print(i) # 列印變數i
888
string = "abc" # 將abc賦值給變數,注意是雙引號
print(string)
abc
string = 'abcd' # 將abcd重新賦值給變數,注意單引號
print(string)
abcd
del string # 刪除變數string
string # 執行變數string
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-5-c0ce0be654d5> in <module>
      1 del string # 刪除變數string
----> 2 string # 執行變數string


NameError: name 'string' is not defined

變數運算--算數運算

a = 888
b = 3
a + b
891
a - b
885
a * b
2664
a / b
296.0
a % b # 取餘
0
a // b # 取商
296
a ** b # 指數
700227072

常用運算函式

abs(-3) # 絕對值
3
round(5.6) # 四捨五入,不保留小數
6
round(5.646,1) # 四捨五入,保留1位小數
5.6
pow(9,2) # 平方
81
pow(9,1/2) # 開根號
3.0
sum([1,2,3,4,5,6]) # 對列表求和
21

比較運算

a > b
True
a < b
False
a == b
False
a != b
True

邏輯運算

a == 3 or b == 3 # 或
True
a == 3 and b ==3 # 與
False
not(a == 3 and b ==3) # 非
True
True == 1
True
True * 2
2
False == 0
True
False * 2
0

3.1 基本資料型別

數字

type(666) # int
int
type(6.66) # float
float
type("6.66") # string
str
type('6.66') # string
str
isinstance('6.66',float) # 判斷浮點型
False
a = 6.66
isinstance(a,float) # 判斷浮點型
True
666 == 666.00
True

字串

單雙引號問題

print("'hello world'") #雙引號巢狀單引號
'hello world'
print('"hello world"') #單引號巢狀雙引號
"hello world"
'' # 空字串
''
len('') # 空字串長度
0
len(' ') # 非空字串長度
1

常用轉義符

print("hello\tworld") #\t 製表符,4個空格,鍵盤【tab】鍵
hello	world
print("hello\nworld") #\n 換行符
hello
world
print("\\t") # 列印 \t
\t

常用字串操作

str1 = "HELLO"
str2 = "world"
print(str1.lower()) # 轉小寫
print(str2.upper()) # 轉大寫
hello
WORLD
str1 = "hello"
str2 = "world"
print(str1 + "\t" + str2) # 拼接
hello	world
",".join(str1) # 插入
'h,e,l,l,o'
str3 = str1 + "\t" + str2
str3.split("\t") # 分隔,輸出“列表(list)”
['hello', 'world']
str1[0] # 第一個字元
'h'
str1[-1] # 倒數第一個字元
'o'
str1[0] = 'b' # 不可修改,報錯
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-22-069543d164da> in <module>
----> 1 str1[0] = 'b' # 不可修改,報錯


TypeError: 'str' object does not support item assignment
str1[1:] # 切片,輸出第二個到最後
'ello'
str1[0:4:2] # 起始位置,結束位置,間隔(步長)
'hl'

字串操作進階

提取字串中的數字、字母、大小寫字母

方法1:for迴圈
  • str.isdigit() 判斷數字
  • str.islower() 判斷小寫
  • str.isupper() 判斷大寫
str1 = "AAaaa22"
number = ""
lower = ""
upper = ""
for i in str1:
    if i.isdigit():
        number += i
    elif i.islower():
        lower += i
    elif i.isupper():
        upper += i
print(number + '\n'
     + lower + '\n'
     + upper)
22
aaa
AA
方法2:正則表示式

\d 匹配任意數字,等價於[0-9]

[0-9] 匹配數字

\D 匹配任意非數字

[a-z] 匹配小寫

[A-Z] 匹配大寫

[a-zA-Z0-9] 匹配數字和字母

import re #載入正則表示式re模組
str1 = '[email protected]'
print(''.join(re.findall(r'[A-Za-z]',str1))) # 提取字母
print(''.join(re.findall(r'[0-9]',str1))) # 提取數字
print(re.sub("\D","",str1)) # 提取數字,將非數字替換為空字元
AAaaaqqcom
22
22

數字型別轉換

float(6) # int→float
6.0
int(6.66) # float→int
6
float("6.66") # str→float
6.66
int("6.66") # str→int,失敗
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-15-55f008fa896e> in <module>
----> 1 int("6.66") # str→int,失敗


ValueError: invalid literal for int() with base 10: '6.66'

3.2 容器

列表(list)

  • 列表是有序集合:可以通過index或者key訪問
  • 購物車(注意與陣列的差別,陣列只能一種型別): 整型、浮點行、字串、列表、字典、元組
  • 支援操作:插入、新增、刪除、修改、排序、反轉
  • 無序集合:只能遍歷訪問

建立列表

list1 = [] # 空列表
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)] # 整型、浮點型、字串、列表、字典、元組
list(range(1,11)) # 自動生成1-10列表
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

新增元素

  • 拼接
  • 複製(自身拼接)
  • list.extend(列表/元組)
  • list.append(元素)
  • list.insert(索引,元素)
# 新增元素
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1.append([4,5,6])
print(list1)
[1, 2.0, '3', [4, 5, 6], {'a': 7, 'b': 8}, ('A', 9), [4, 5, 6]]
# 新增元素--不推薦
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1[len(list1):len(list1)] = [[4,5,6]]
print(list1)
[1, 2.0, '3', [4, 5, 6], {'a': 7, 'b': 8}, ('A', 9), [4, 5, 6]]
# 批量新增元素
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1.extend([4,5,6]) # 會展開,遍歷元素插入
list1.extend(('A',9)) # 會展開,遍歷元素插入
print(list1)
[1, 2.0, '3', [4, 5, 6], {'a': 7, 'b': 8}, ('A', 9), 4, 5, 6, 'A', 9]
# 批量新增元素(拼接)
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1 += [4,5,6]
list1 += ('A',9)
print(list1)
[1, 2.0, '3', [4, 5, 6], {'a': 7, 'b': 8}, ('A', 9), 4, 5, 6, 'A', 9]
# 複製(自身拼接)
list1 = [6] * 3
print(list1)
[6, 6, 6]
# 拼接
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list2 = [4,5,6]
print(list1 + list2)
[1, 2.0, '3', [4, 5, 6], {'a': 7, 'b': 8}, ('A', 9), 4, 5, 6]
# 指定位置插入
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1.insert(3,[7,8,9])
print(list1)
[1, 2.0, '3', [4, 5, 6], [4, 5, 6], {'a': 7, 'b': 8}, ('A', 9)]
# 指定位置插入--不推薦
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1[3:3] = [[7,8,9]]
print(list1)
[1, 2.0, '3', [7, 8, 9], [4, 5, 6], {'a': 7, 'b': 8}, ('A', 9)]

查詢

# 列表長度
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
len(list1) # 長度
6
1 in [1,2,3] # 判斷元素是否在列表內
True
# 元素索引
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1.index([4,5,6]) # 索引
3
# 統計元素
list1 = [1,2,3,6,6,6]
list1.count(6)
3
# 獲取最值--確保列表內元素是相同型別(陣列)
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
max(list1) # 最大值
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-38-e286fb0cfffb> in <module>
      1 list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
----> 2 max(list1) # 最大值


TypeError: '>' not supported between instances of 'str' and 'float'
# 獲取最值--列表作為元素
list1 = [[4,5,6,7],[5,3,8,2],[6,6,6]] # 只比較第一個數
print(max(list1)) # 最大值
print(min(list1)) # 最小值
[6, 6, 6]
[4, 5, 6, 7]

刪除

  • list.pop(索引)
  • list.remove(元素)
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1.pop(3)
print(list1)
[1, 2.0, '3', {'a': 7, 'b': 8}, ('A', 9)]
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1.remove([4,5,6])
print(list1)
[1, 2.0, '3', {'a': 7, 'b': 8}, ('A', 9)]

排序

# 排序前提:確保資料型別相同
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1.sort(reverse=True)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-9-50eede7c89b5> in <module>
      1 list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
----> 2 list1.sort(reverse=True)


TypeError: '<' not supported between instances of 'dict' and 'tuple'
list1 = [5,2,6,8,6.8,6,1]
list1.sort() # 升序
print(list1)
list1.sort(reverse = True) #降序
print(list1)
[1, 2, 5, 6, 6, 6.8, 8]
[8, 6.8, 6, 6, 5, 2, 1]

其他操作

  • 反向
  • 切片(跟字串一樣)
# 反向
list1 = [1,2.0,'3',[4,5,6],{"a":7,"b":8},('A',9)]
list1.reverse()
print(list1)
[('A', 9), {'a': 7, 'b': 8}, [4, 5, 6], '3', 2.0, 1]

元組(tuple)

元素不可修改(只讀)

tuple1 = () # 建立空元組
type(tuple1)
tuple
tuple1 = (1,) # 必需有逗號
type(tuple1)
tuple

集合(set)

無重複元素

  • 新增
    • set.add(元素)
    • set.update(容器)
  • 刪除
    • set.remove(元素)
  • 運算
    • 並集 |
    • 交集 &
    • 差集 -
    • 交集的補集 ^
set1 = set() # 建立空集合
type(set1)
set
set1 = {1}
type(set1)
set
set1 = {1,1,2,3,4} # 去重操作
print(set1)
{1, 2, 3, 4}
# 新增元素
set1 = {1,2,3,4}
set1.add(5)
print(set1)
{1, 2, 3, 4, 5}
# 新增集合
set1 = {1,2,3,4}
tuple1 = (5,)
set1.update(tuple1)
print(set1)
{1, 2, 3, 4, 5}
# 刪除元素
set1 = {1,2,3,4,5}
set1.remove(5)
print(set1)
{1, 2, 3, 4}
# 並集
set1 = {1,2,3,4}
set2 = {1,5,6}
set3 = set1 | set2
print(set3)
{1, 2, 3, 4, 5, 6}
# 差集
set1 = {1,2,3,4}
set2 = {1,5,6}
set3 = set1 - set2
print(set3)
{2, 3, 4}
# 交集
set1 = {1,2,3,4}
set2 = {1,5,6}
set3 = set1 & set2
print(set3)
{1}
# 交集的補集
set1 = {1,2,3,4}
set2 = {1,2,5,6}
set3 = set1 ^ set2
print(set3)
{3, 4, 5, 6}

字典(dict)

key-value(鍵值對),json

# 建立空字典
dict1 = {}
type(dict1)
dict
# 用列表建立字典
name = ["張三","李四"]
phone = ["16666666666","18888888888"]
dict1 = dict(zip(name,phone))
print(dict1)
{'張三': '16666666666', '李四': '18888888888'}

4 流程控制

4.1 順序結構

程式從上到下按順序執行語句

分支結構

# 求a,b,c的最大值
a = 8
b = 9
c = 6
if a>b and a>c:
    print(a)
elif b>a and b>c:
    print(b)
else:
    print(c)
9
# 求a,b,c的最大值(巢狀)
a = 8
b = 9
c = 6
if a>b:
    if a>c:
        print(a)
    else:
        print(c)
elif b>c:
    print(b)
else:
    print(c)
9

4.2 迴圈結構

while迴圈

# 求和(前100)
num = 1
sum = 0
while num<=100:
    sum += num
    num += 1
print(sum)
5050

for迴圈

# 求和(前100)
sum = 0
for i in range(1,101):
    sum += i
print(sum)
5050
# 奇數和(前100)
sum = 0
for i in range(1,101,2):
    sum += i
print(sum)
2500

5 函式與類

函式(function)

包裝,封裝成一個個黑盒子(會用就行),不關注如何執行,只關注輸入、輸出

def(define縮寫) 函式名(引數):
    語句1
    語句2
    return 返回值
# 封裝“打招呼”函式
def sayHi(name,sex):
    if(sex == '男'):
        print("{0}{1},您好!".format(name,"先生"))
    else:
        print(f"{name}女士,您好!")
    return None #可以省略

name = input("請輸入您的名字:")
sex = input("請輸入您的性別:")
sayHi(name,sex)
請輸入您的名字:劉小貝
請輸入您的性別:女
劉小貝女士,您好!

類(Class)

  • 封裝性,可以把資料函式打包在一起
  • 抽象性,類(class)是抽象的,可以理解為模板,用的時候必需例項化為一個個物件(Instance)
  • 繼承性,子類繼承父類的所有資料函式
# 定義類
class Student(object):
    # 封裝資料--屬性成員,第一個引數self是指自身
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex
    # 封裝函式--方法成員,第一個引數self是指自身
    def Eat(self):
        print(f"{self.name}在直播吃粑粑。。。")
    def Sleep(self):
        print(f"{self.name}睡的像豬一樣!!!")
    def Social(self):
        if self.sex=='男':
            print(f"{self.name}在泡妹紙~~~")
        else:
            print(f"{self.name}在泡馬子~~~")

# 例項化物件
XiaoBei = Student("劉小貝","男")
XiaoBei.Eat()
XiaoBei.Sleep()
XiaoBei.Social()
劉小貝在直播吃粑粑。。。
劉小貝睡的像豬一樣!!!
劉小貝在泡妹紙~~~

6 檔案讀寫

6.1 內建讀寫

# 宣告變數
title = ''
time = ''
author = ''
poem = []

def SaveFile(fileName,writedContext):
    poemFile = open(fileName,'w')
    poemFile.writelines(writedContext)
    poemFile.close()

# 開啟檔案(讀),跟本程式檔案相同資料夾
f = open("詩詞.txt",encoding="UTF-8")
# 讀取檔案
lines = f.readlines()
for line in lines:
    # 獲取檔名
    if('\t' in line):
        if  '-' in line:
            temp = line.strip('-\t\n')
            templist = temp.split(':')
            time = '['+templist[0]+']'
            author = templist[1]
        else:
            title = '《'+line.strip()+'》'
        fileName = title + time + author + '.txt'
    # 分隔詩詞
    if(line[:6] != '======'):
        poem.append(line)
    else:
        SaveFile(fileName,poem)
        poem = []
        
SaveFile(fileName,poem)        
f.close()

6.2 Pandas讀寫

import pandas as pd # 匯入模組並命名為pd
df = pd.read_csv('個人資訊表.csv')
df.to_csv("個人資訊表_副本.csv",index=False)

7 Pandas資料分析