python編程語言中有一些常用的數據結構,熟悉這些數據結構和常用方法是進一步使用python進行數據分析的基礎。
String
字符串是所有編程語言中最常見的數據結構,在Python中,字符串的操作和定義和其他編程語言也大致相同。
首先是定義一個字符串,在python中,可以使用單引號或者雙引號進行定義。同時如果一個字符串要跨越多行,可以使用"""
或者'''
進行定義:
str1 = "hello"
str2 = 'hello'
str3 = """
this is a mulitple line string
this is a multiple line string
"""
對於字符串的截取操作,python支持[num1, num2]
,[num1]
,[:num2]
和[num1:]
等多種形式。是"左閉右開"的方式:
str1 = "hello"
print(str1[0:2]) # he
print(str1[2]) # l
print(str1[:3]) # 省略頭部,相當於從0開始, hel
print(str1[:-1]) # 負數相當於從右往左數 hell
python還支持第三個參數,用它可以指明跳過的數值,默認是1
print(str1[::2]) # hlo
format
字符串中一個比較常用的操作是格式化,可以使用format
這個方法進行處理,在字符串中佔位符,使用{}
進行記錄。
str = 'Hello, I am {}, I am {} years old'.format('scq000', 23)
print(str) # 'Hello, I am scq000, I am 23 years old'
還有一種定義格式化字符串的方式使用f
開頭的字符串:
name = 'scq000'
age = 23
data = f'Hello, {name}, I am {age}'
這裏詳細的接口和用法,可以參考:https://www.python.org/dev/peps/pep-0498/
find
在一個字符串中查找子字符串所在的位置也是常見操作,可以使用find
接口:
"sdfsdfds".find("fd") # 5
split
將字符串安裝分隔符進行分割,可以使用split
方法:
"hello world".split(" ") # ["hello", "world"]
"hello,world".split(",") # ["hello", "world"]
strip
去除字符串前後多餘的空格,可以採用strip
方法:
" sfsdf fdsfs and ".strip() # 'sfsdf fdsfs and'
join
將一個列表用字符串進行合併,可以採用join
方法:
data = ['hello','world']
", ".join(data) # 'hello, world'
List
列表(或數組)是用來存儲順序數據的一種常用數據結構,創建一個列表有以下幾種方式:
list1 = [] # 空列表
list2 = [1,2,3] # 帶數據的列表
list3 = list() # 利用list構造函數進行聲明
Python中的列表常用操作有以下幾種:
常用方法 | 作用 | 例子 |
---|---|---|
append | 在列表末尾加入一個元素 | data.append(1) |
insert | 在列表特定位置插入一個元素 | data.insert(1, '2') |
del | 刪除特定位置的元素 | del data[2] |
remove | 刪除特定值的元素 | data.remove(10) |
clear | 刪除列表中的所有元素 | data.clear() |
sort | 排序 | data.sort() |
reverse | 翻轉列表 | data.reverse() |
由於修改列表中的數據勢必會影響原數據,所以在操作過程中,經常會用到深度拷貝的操作:
data = [1,2,3,4]
d = data[:] #簡便寫法
# 後續操作d列表,就不會影響到原來的data列表了
另外,還有一些通用的接口在日常編程中十分常見:
操作 | 描述 |
---|---|
v in s | 判斷值是否在s中 |
v not in s | 判斷值是否不在s中 |
s + t | 合併兩個列表生成新的列表 |
s * n or n * s | 乘以一個數字,可以擴展對應的列表 |
min(s) | 取得最小值 |
len(s) | 獲取長度 |
max(s) | 取得最大值 |
s.count(v) | 值v在s中出現了幾次 |
比如:
data = [1,2,3,4]
1 in data # True
0 not in data # True
data * 2 # [1,2,3,4,1,2,3,4]
data + [5,4,3,2,1] # [1,2,3,4,5,4,3,2,1]
print(data.count(2)) # 1
print(len(data), min(data), max(data)) # 4, 1, 4
Tuple
元組是python中一種特殊的數據結構,它的特定是不能其中的元素不能修改。定義方式使用常見的()
進行定義,如:
tup2 = (1,2,3,4)
tup2 = 1, 2, 3 # 可以省略括號
tup3 = tuple() #使用構造函數
雖然元組中的數據不能被修改,不過我們可以使用多個元組進行組合生成新的元組:
tup1 = (1,2,3)
tup2 = (4,5,6)
tup3 = tup1 + tup2
x, y, z = tup2
# x == 4, y == 5, z == 6
Dictionary
字典是一個由鍵值對組成的對象,創建一個字典對象可以使用如下方式:
dict1 = {} #空字典
dict2 = {'1': 1}
dict3 = dict() # 使用構造函數創建字典
針對一個字典對象,Python提供了很多和列表類似的接口進行操作:
常用操作 | 作用 | 例子 |
---|---|---|
v in d | 判斷某個值是否在字典中 | '1' in dict1 |
v not in d | 判斷某個值是否不在字典中 | '1' not in dict1 |
del d[k] | 刪除特定鍵值對 | del d['1'] |
d.keys() | 列出所有的鍵 | dict1.keys() |
d.values() | 列出所有的值 | dict1.values() |
d.items() | 列出所有的鍵值對 | dict1.items() |
d.clear() | 清空字典 | dict1.clear() |
d.copy() | 淺拷貝一個字典 | dict1.copy() |
len(d) | 獲取鍵值對個數 | len(dict1) |
其他數據結構
python目前還提供了很多實用的數據結構,包括:range, set, frozense和collections模塊中的一系列數據結構,大家可以根據自身需要進行學習:
https://docs.python.org/3/library/stdtypes.html#range
https://docs.python.org/3/library/stdtypes.html#set
https://docs.python.org/3/library/collections.html
function
函數的創建由def
關鍵字開頭進行定義:
def hello():
print("hello world")
創建一個有返回值的函數:
def sum(a, b):
return a + b
print(sum(1,2)) # 3
另外一種定義匿名函數的方式是使用lambda函數:
f = lambda x, y: x**y + y**2
File I/O
操作文件是可以使用以下這些接口:
f = open("tempfile", "w")
其中第二個參數是文件描述符,"w"對應write,"r"對應read,"a"對應append等。對此,可以參考https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files這篇文檔。
使用python程序讀寫文件的最佳實踐是使用with
語句,即使程序運行過程中發生錯誤,文件也能夠被合適地關閉,如果不是用with
語句,那麼你需要顯式地使用close
方法進行釋放文件資源。
with open('temp.txt', 'a') as fout:
fout.write("hello")
import numpy
在操作json格式的文件時,可以使用json
模塊:
import json
f1 = open("temp.json", 'w')
json.dump([1, 'hello'], f1) #將json對象寫入文件
f1 = f1.close()
f2 = open("temp.json", 'r')
x = json.load(f2) # x = [1, 'hello']