13個Python必備的知識,建議收藏!

數據分析那些事
17 min readJun 21, 2022

--

Python在程式語言流行指數PYPL中已多次排名第一。

由於其程式碼可讀性和更簡單的語法,它被認為是有史以來最簡單的語言。

NumPy、Pandas、TensorFlow等各種AI和機器學習庫的豐富性,是Python核心需求之一。

如果你是資料科學家或 AI/機器學習的初學者,那麼Python是開始你的旅程的正確選擇。

本次,帶著大家探索一些Python程式設計的基礎知識,雖然簡單但都很有用。

目錄

資料型別

變數

列表

集合

字典

註釋

基本功能

條件語句

迴圈語句

函式

異常處理

字串操作

正則表示式

▍1、資料型別

資料型別是可以儲存在變數中的資料規範。直譯器根據變數的型別為變數分配記憶體。

下面是Python中的各種資料型別。

▍2、變數

變數是存放資料值的容器。

變數可以使用短名稱(如x和y)或更具描述性的名稱(age、carname、total_volume)。

Python 變數命名規則:

變數名必須以字母或下劃線字元開頭

變數名稱不能以數字開頭

變數名只能包含字母數字字元和下劃線(A-z、0–9和_)

變數名稱區分大小寫(age、Age和AGE是三個不同的變數)

var1 = ‘Hello World’
var2 = 16
_unuseful = ‘Single use variables’

輸出結果如下。

▍3、列表

列表(List)是一種有序和可更改的集合,允許重複的成員。

它可能不是同質的,我們可以建立一個包含不同資料型別(如整數、字串和物件)的列表。‍

>>> companies = [“apple”,”google”,”tcs”,”accenture”]
>>> print(companies)
[‘apple’, ‘google’, ‘tcs’, ‘accenture’]
>>> companies.append(“infosys”)
>>> print(companies)
[‘apple’, ‘google’, ‘tcs’, ‘accenture’, ‘infosys’]
>>> print(len(companies))
5
>>> print(companies[2])
tcs
>>> print(companies[-2])
accenture
>>> print(companies[1:])
[‘google’, ‘tcs’, ‘accenture’, ‘infosys’]
>>> print(companies[:1])
[‘apple’]
>>> print(companies[1:3])
[‘google’, ‘tcs’]
>>> companies.remove(“infosys”)
>>> print(companies)
[“apple”,”google”,”tcs”,”accenture”]
>>> companies.pop()
>>> print(companies)
[“apple”,”google”,”tcs”]

▍4、集合

集合(Set)是一個無序和無索引的集合,沒有重複的成員。

對於從列表中刪除重複條目非常有用。它還支援各種數學運算,例如並集、交集和差分。

>>> set1 = {1,2,3,7,8,9,3,8,1}
>>> print(set1)
{1, 2, 3, 7, 8, 9}
>>> set1.add(5)
>>> set1.remove(9)
>>> print(set1)
{1, 2, 3, 5, 7, 8}
>>> set2 = {1,2,6,4,2}
>>> print(set2)
{1, 2, 4, 6}
>>> print(set1.union(set2)) # set1 | set2
{1, 2, 3, 4, 5, 6, 7, 8}
>>> print(set1.intersection(set2)) # set1 & set2
{1, 2}
>>> print(set1.difference(set2)) # set1 — set2
{8, 3, 5, 7}
>>> print(set2.difference(set1)) # set2 — set1
{4, 6}

▍5、字典

字典是作為鍵值對的可變無序項集合。

與其他資料型別不同,它以【鍵:值】對格式儲存資料,而不是儲存單個數據。此功能使其成為對映JSON響應的最佳資料結構。

>>> # example 1
>>> user = { ‘username’: ‘Fan’, ‘age’: 20, ‘mail_id’: ‘codemaker2022@qq.com’, ‘phone’: ‘18650886088’ }
>>> print(user)
{‘mail_id’: ‘codemaker2022@qq.com’, ‘age’: 20, ‘username’: ‘Fan’, ‘phone’: ‘18650886088’}
>>> print(user[‘age’])
20
>>> for key in user.keys():
>>> print(key)
mail_id
age
username
phone
>>> for value in user.values():
>>> print(value)
codemaker2022@qq.com
20
Fan
18650886088
>>> for item in user.items():
>>> print(item)
(‘mail_id’, ‘codemaker2022@qq.com’)
(‘age’, 20)
(‘username’, ‘Fan’)
(‘phone’, ‘18650886088’)
>>> # example 2
>>> user = {
>>> ‘username’: “Fan”,
>>> ‘social_media’: [
>>> {
>>> ‘name’: “Linkedin”,
>>> ‘url’: “https://www.linkedin.com/in/codemaker2022
>>> },
>>> {
>>> ‘name’: “Github”,
>>> ‘url’: “https://github.com/codemaker2022
>>> },
>>> {
>>> ‘name’: “QQ”,
>>> ‘url’: “https://codemaker2022.qq.com
>>> }
>>> ],
>>> ‘contact’: [
>>> {
>>> ‘mail’: [
>>> “mail.Fan@sina.com”,
>>> “codemaker2022@qq.com
>>> ],
>>> ‘phone’: “18650886088”
>>> }
>>> ]
>>> }
>>> print(user)
{‘username’: ‘Fan’, ‘social_media’: [{‘url’: ‘https://www.linkedin.com/in/codemaker2022’, ‘name’: ‘Linkedin’}, {‘url’: ‘https://github.com/codemaker2022’, ‘name’: ‘Github’}, {‘url’: ‘https://codemaker2022.qq.com', ‘name’: ‘QQ’}], ‘contact’: [{‘phone’: ‘18650886088’, ‘mail’: [‘mail.Fan@sina.com’, ‘codemaker2022@qq.com’]}]}
>>> print(user[‘social_media’][0][‘url’])
https://www.linkedin.com/in/codemaker2022
>>> print(user[‘contact’])
[{‘phone’: ‘18650886088’, ‘mail’: [‘mail.Fan@sina.com’, ‘codemaker2022@qq.com’]}]

▍6、註釋

單行註釋,以井字元(#)開頭,後面帶有訊息並在行尾結束。

# 定義使用者年齡
age = 27
dob = ‘16/12/1994’ # 定義使用者生日

多行註釋,用特殊引號(“””)括起來,你可以將訊息放在多行中。

“””
Python小常識
This is a multi line comment
“””

▍7、基本功能

print()函式在控制檯中列印提供的訊息。此外你還可以提供檔案或緩衝區輸入作為在螢幕上列印的引數。

print(object(s), sep=separator, end=end, file=file, flush=flush)print(“Hello World”) # prints Hello World 
print(“Hello”, “World”) # prints Hello World?
x = (“AA”, “BB”, “CC”)
print(x) # prints (‘AA’, ‘BB’, ‘CC’)
print(“Hello”, “World”, sep=” — -”) # prints Hello — -World

input()函式用於收集來自控制檯的使用者輸入 。

這裡需要注意,input()會把你輸入的任何內容轉換為字串。

因此,如果你將年齡作為整數值提供,但input()方法將其作為字串返回,此時就需要手動將其轉換為整數。

>>> name = input(“Enter your name: “)
Enter your name: Codemaker
>>> print(“Hello”, name)
Hello Codemaker

len()可以檢視物件的長度。如果你輸入一個字串,則可以獲取指定字串中的字元數。

>>> str1 = “Hello World”
>>> print(“The length of the string is “, len(str1))
The length of the string is 11

str()用於將其他資料型別轉換為字串值。

>>> str(123)
123
>>> str(3.14)
3.14

int()用於將字串轉換為整數。

>>> int(“123”)
123
>>> int(3.14)
3

▍8、條件語句

條件語句是用於根據特定條件更改程式流程的程式碼塊。這些語句只有在滿足特定條件時才會執行。

在Python中,我們使用if,if-else,迴圈(for,while)作為條件語句根據某些條件來改變程式的流程。

if-else語句。

>>> num = 5
>>> if (num > 0):
>>> print(“Positive integer”)
>>> else:
>>> print(“Negative integer”)

elif語句。

>>> name = ‘admin’
>>> if name == ‘User1’:
>>> print(‘Only read access’)
>>> elif name == ‘admin’:
>>> print(‘Having read and write access’)
>>> else:
>>> print(‘Invalid user’)
Having read and write access

▍9、迴圈語句

迴圈是一個條件語句,用於重複某些語句(在其主體中),直到滿足某個條件。

在Python中,我們通常使用for和while迴圈。

for迴圈。

>>> # loop through a list
>>> companies = [“apple”, “google”, “tcs”]
>>> for x in companies:
>>> print(x)
apple
google
tcs
>>> # loop through string
>>> for x in “TCS”:
>>> print(x)
T
C
S

range()函式返回一個數字序列,它可以用作for迴圈控制。

它基本上需要三個引數,其中第二個和第三個是可選的。引數是開始值、停止值和步進數。步進數是每次迭代迴圈變數的增量值。

>>> # loop with range() function
>>> for x in range(5):
>>> print(x)
0
1
2
3
4
>>> for x in range(2, 5):
>>> print(x)
2
3
4
>>> for x in range(2, 10, 3):
>>> print(x)
2
5
8

我們還可以使用else關鍵字在迴圈結束時執行一些語句。

在迴圈結束時提供else語句以及迴圈結束時需要執行的語句。

>>> for x in range(5):
>>> print(x)
>>> else:
>>> print(“finished”)
0
1
2
3
4
finished

while迴圈。

>>> count = 0
>>> while (count < 5):
>>> print(count)
>>> count = count + 1
0
1
2
3
4

我們可以在while迴圈的末尾使用else,類似於for迴圈,當條件為假時執行一些語句。

>>> count = 0
>>> while (count < 5):
>>> print(count)
>>> count = count + 1
>>> else:
>>> print(“Count is greater than 4”)
0
1
2
3
4
Count is greater than 4

▍10、函式

函式是用於執行任務的可重用程式碼塊。在程式碼中實現模組化並使程式碼可重用,這是非常有用的。

>>> # This prints a passed string into this function
>>> def display(str):
>>> print(str)
>>> return
>>> display(“Hello World”)
Hello World

▍11、異常處理

即使語句在語法上是正確的,它也可能在執行時發生錯誤。這些型別的錯誤稱為異常。我們可以使用異常處理機制來避免此類問題。

在Python中,我們使用try,except和finally關鍵字在程式碼中實現異常處理。

>>> def divider(num1, num2):
>>> try:
>>> return num1 / num2
>>> except ZeroDivisionError as e:
>>> print(‘Error: Invalid argument: {}’.format(e))
>>> finally:
>>> print(“finished”)
>>>
>>> print(divider(2,1))
>>> print(divider(2,0))
finished
2.0
Error: Invalid argument: division by zero
finished
None

▍12、字串操作

字串是用單引號或雙引號(‘,”)括起來的字元集合。

我們可以使用內建方法對字串執行各種操作,如連線、切片、修剪、反轉、大小寫更改和格式化,如split()、lower()、upper()、endswith()、join()和ljust()、rjust()、format()。

>>> msg = ‘Hello World’
>>> print(msg)
Hello World
>>> print(msg[1])
e
>>> print(msg[-1])
d
>>> print(msg[:1])
H
>>> print(msg[1:])
ello World
>>> print(msg[:-1])
Hello Worl
>>> print(msg[::-1])
dlroW olleH
>>> print(msg[1:5])
ello
>>> print(msg.upper())
HELLO WORLD
>>> print(msg.lower())
hello world
>>> print(msg.startswith(‘Hello’))
True
>>> print(msg.endswith(‘World’))
True
>>> print(‘, ‘.join([‘Hello’, ‘World’, ‘2022’]))
Hello, World, 2022
>>> print(‘ ‘.join([‘Hello’, ‘World’, ‘2022’]))
Hello World 2022
>>> print(“Hello World 2022”.split())
[‘Hello’, ‘World’, ‘2022’]
>>> print(“Hello World 2022”.rjust(25, ‘-’))
— — — — -Hello World 2022
>>> print(“Hello World 2022”.ljust(25, ‘*’))
Hello World 2022*********
>>> print(“Hello World 2022”.center(25, ‘#’))
#####Hello World 2022####
>>> name = “Codemaker”
>>> print(“Hello %s” % name)
Hello Codemaker
>>> print(“Hello {}”.format(name))
Hello Codemaker
>>> print(“Hello {0}{1}”.format(name, “2022”))
Hello Codemaker2022

▍13、正則表示式

匯入regex模組,import re。

re.compile()使用該函式建立一個Regex物件。

將搜尋字串傳遞給search()方法。

呼叫group()方法返回匹配的文字。

>>> import re
>>> phone_num_regex = re.compile(r’\d\d\d-\d\d\d-\d\d\d\d’)
>>> mob = phone_num_regex.search(‘My number is 996–190–7453.’)
>>> print(‘Phone number found: {}’.format(mob.group()))
Phone number found: 996–190–7453
>>> phone_num_regex = re.compile(r’^\d+$’)
>>> is_valid = phone_num_regex.search(‘+919961907453.’) is None
>>> print(is_valid)
True
>>> at_regex = re.compile(r’.at’)
>>> strs = at_regex.findall(‘The cat in the hat sat on the mat.’)
>>> print(strs)
[‘cat’, ‘hat’, ‘sat’, ‘mat’]

好了,本期的分享就到此結束了,有興趣的小夥伴可以自行去實踐學習。

文章來源於可樂的資料分析之路

文章連結:https://mp.weixin.qq.com/s/bFWkwiERK8P3OUJ5t91rhg

立即試用FineBI免費版:

https://intl.finebi.com/zh-tw/trial?utm_source=Medium_Banner

※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※

我是「數據分析那些事」。常年分享數據分析乾貨,不定期分享好用的職場技能工具。各位也可以關注我的Facebook,按讚我的臉書並私訊「10」,送你十週入門數據分析電子書唷!期待你與我互動起來~

文章推薦

餅圖變形記,肝了3000字,收藏就是學會!

MySQL必須掌握4種語言!

太實用了!4種方法教你輕鬆製作互動式儀表板!

跟資料打交道的人都得會的這8種資料模型,滿足工作中95%的需求

妙呀!一行Python程式碼

--

--

數據分析那些事
數據分析那些事

Written by 數據分析那些事

這是一個專注於數據分析職場的內容部落格,聚焦一批數據分析愛好者,在這裡,我會分享數據分析相關知識點推送、(工具/書籍)等推薦、職場心得、熱點資訊剖析以及資源大盤點,希望同樣熱愛數據的我們一同進步! 臉書會有更多互動喔:https://www.facebook.com/shujvfenxi/

No responses yet