python編程語言中有一些常用的數(shù)據(jù)結(jié)構(gòu),熟悉這些數(shù)據(jù)結(jié)構(gòu)和常用方法是進一步使用python進行數(shù)據(jù)分析的基礎(chǔ)昼牛。
String
字符串是所有編程語言中最常見的數(shù)據(jù)結(jié)構(gòu),在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]) # 負數(shù)相當于從右往左數(shù) hell
python還支持第三個參數(shù)绸罗,用它可以指明跳過的數(shù)值,默認是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
列表(或數(shù)組)是用來存儲順序數(shù)據(jù)的一種常用數(shù)據(jù)結(jié)構(gòu)趟薄,創(chuàng)建一個列表有以下幾種方式:
list1 = [] # 空列表
list2 = [1,2,3] # 帶數(shù)據(jù)的列表
list3 = list() # 利用list構(gòu)造函數(shù)進行聲明
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 | 翻轉(zhuǎn)列表 | data.reverse() |
由于修改列表中的數(shù)據(jù)勢必會影響原數(shù)據(jù)绽诚,所以在操作過程中,經(jīng)常會用到深度拷貝的操作:
data = [1,2,3,4]
d = data[:] #簡便寫法
# 后續(xù)操作d列表杭煎,就不會影響到原來的data列表了
另外恩够,還有一些通用的接口在日常編程中十分常見:
操作 | 描述 |
---|---|
v in s | 判斷值是否在s中 |
v not in s | 判斷值是否不在s中 |
s + t | 合并兩個列表生成新的列表 |
s * n or n * s | 乘以一個數(shù)字,可以擴展對應(yīng)的列表 |
min(s) | 取得最小值 |
len(s) | 獲取長度 |
max(s) | 取得最大值 |
s.count(v) | 值v在s中出現(xiàn)了幾次 |
比如:
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中一種特殊的數(shù)據(jù)結(jié)構(gòu)羡铲,它的特定是不能其中的元素不能修改蜂桶。定義方式使用常見的()
進行定義,如:
tup2 = (1,2,3,4)
tup2 = 1, 2, 3 # 可以省略括號
tup3 = tuple() #使用構(gòu)造函數(shù)
雖然元組中的數(shù)據(jù)不能被修改也切,不過我們可以使用多個元組進行組合生成新的元組:
tup1 = (1,2,3)
tup2 = (4,5,6)
tup3 = tup1 + tup2
x, y, z = tup2
# x == 4, y == 5, z == 6
Dictionary
字典是一個由鍵值對組成的對象扑媚,創(chuàng)建一個字典對象可以使用如下方式:
dict1 = {} #空字典
dict2 = {'1': 1}
dict3 = dict() # 使用構(gòu)造函數(shù)創(chuàng)建字典
針對一個字典對象,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) | 獲取鍵值對個數(shù) | len(dict1) |
其他數(shù)據(jù)結(jié)構(gòu)
python目前還提供了很多實用的數(shù)據(jù)結(jié)構(gòu)雷恃,包括:range, set, frozense和collections模塊中的一系列數(shù)據(jù)結(jié)構(gòu)疆股,大家可以根據(jù)自身需要進行學習:
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
函數(shù)的創(chuàng)建由def
關(guān)鍵字開頭進行定義:
def hello():
print("hello world")
創(chuàng)建一個有返回值的函數(shù):
def sum(a, b):
return a + b
print(sum(1,2)) # 3
另外一種定義匿名函數(shù)的方式是使用lambda函數(shù):
f = lambda x, y: x**y + y**2
File I/O
操作文件是可以使用以下這些接口:
f = open("tempfile", "w")
其中第二個參數(shù)是文件描述符,"w"對應(yīng)write,"r"對應(yīng)read倒槐,"a"對應(yīng)append等旬痹。對此,可以參考https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files這篇文檔。
使用python程序讀寫文件的最佳實踐是使用with
語句两残,即使程序運行過程中發(fā)生錯誤永毅,文件也能夠被合適地關(guān)閉,如果不是用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']