?? 幾種常見數(shù)據(jù)結構
列表 (List)
1. 定義
列表是一種有序的可變序列
,可以包含不同類型的元素。列表可以通過方括號 []
來表示,元素之間用逗號分隔
。
注釋: 注意列表可變,字符串不可變,只能改變大小寫
2. 實例:
my_list = [1, 'hello', 3.14, True]
3. 列表中常用方法
.append(要添加內容) 向列表末尾添加數(shù)據(jù)
.extend(列表) 將可迭代對象逐個添加到列表中
.insert(索引,插入內容) 向指定位置插入內容
.remove(刪除內容) 刪除指定內容
.pop(索引) 刪除指定索引處內容并返回刪除內容
.index(要查詢內容) 返回一個與制定元素匹配的索引,不改變原列表
.count(要查詢內容) 返回列表中該元素出現(xiàn)次數(shù)
.sort() 同類型排序(默認升序),不同類型會報錯TypeError: ‘<’ not supported between instances of ‘int’ and ‘str’
.reverse() 反向排序,不分類型
元組(Tuple)
1. 定義
元組是一種有序的不可變序列
,同樣可以包含不同類型的元素。元組可以通過圓括號 ()
來表示,元素之間用逗號分隔
。
2. 實例:
my_tuple = (1, 'hello', 3.14, True)
元組輸出的是列表的子集
3. 元組中常用方法
因為元組是不可修改的所以只能查詢,如果要修改得先轉換成列表進行修改,之后在轉換成元組
x = (1,5,'i','j')
# x.sort() #報錯 AttributeError: 'tuple' object has no attribute 'sort'
print(x[1]) #輸出: 5
x[1] = 6 #報錯 TypeError: 'tuple' object does not support item assignment
.index(element) 返回第一個與制定元素相等的元素的索引
.count(要查詢內容) 返回列表中該元素出現(xiàn)次數(shù)
修改元組內容
字典(Dictionary)
1. 定義
字典是一種鍵值對
的集合,鍵和值可以是任意的數(shù)據(jù)類型。字典可以通過花括號 {}
來表示,每個鍵值對使用冒號 : 分隔
,鍵值對之間用逗號分隔
??勺鰞热菪薷?/p>
a={age:10}
a['age']=18
print(a) #輸出 {'age': 18}
字典里邊沒有順序 ,列表有從0開始
字典是直接刪除重新加入,所以沒有順序
2. 實例:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
3. 字典中常用方法
in和not in方法
a={'age':10,'name':'xiaoming'}
print('name' in a) #輸出 True
print('s' not in a) #輸出 True
for 鍵 in 字典
可以通過dict(?。?鍵值
for in 和items()結合使用
for 健,鍵值 in 字典.items()
a = {'age':10,'name':'xiaoming'}
for (k,v) in a.items(): #()可加可不加
print(k,v)
print(k,v) 輸出:
age 10
name xiaoming
.keys() 返回一個包含字典所有鍵
的視圖
.values() 返回一個包含字典所有值
的視圖
get(key, default):返回指定鍵的值,如果鍵不存在,則返回默認值(default)。
.pop(key):移除指定鍵的鍵值對,并返回鍵對應的值。
.popitem():隨機移除并返回一個鍵值對
.update(): 使用其他字典內容更新當前字典
.clear():移除字典中的所有鍵值對。
.items() : 用于以鍵-值對(key-value pairs)
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
items = my_dict.items()
print(items)
輸出: dict_items([(‘name’, ‘Alice’), (‘age’, 25), (‘city’, ‘New York’)])
集合(Set)
1. 定義
集合是一種無序的
、不重復
的元素的集合。集合可以通過花括號 {} 或 set() 函數(shù)來創(chuàng)建
。
2. 實例:
my_set = {1, 2, 3, 4, 5}
3. 集合常用方法
.add(element)向集合隨機
添加元素(因為無序所以隨機)
.remove(element)從集合中刪除某元素,如果該集合沒有該元素返回錯誤KeyError
.discard(element)從集合中刪除某元素,如果該集合沒有該元素也不會報錯
.pop()隨機移初一個元素,并返回該元素(集合是無序的,無法確定刪除的元素是那個)
.clear() 清除集合中所有元素,輸出set()
.copy():復制一個集合
字符串(String)
1. 定義
字符串是一種由字符組成的不可變序列
,可以用單引號或雙引號括
起來
2. 實例:
my_string = 'Hello, World!'
3. 集合常用方法
上篇文章有寫,跳轉地址python3 0基礎學習----基本知識
?? 常用的內置函數(shù)
1. print(): 將制定的值輸出到控制臺
print('hi~') #輸出 hi~
2. len(sequence): 返回序列的長度(元素個數(shù))
3. type(object): 返回對象的類型
4. input(‘請輸入’) : 獲取用戶輸入數(shù)據(jù)
5. range(初值, 終值, 步長)內置函數(shù),返回的是一個可迭代對象。用于創(chuàng)建數(shù)字序列
for num in range(5):
print(num) # 輸出: 0, 1, 2, 3, 4
for num in range(2, 7):
print(num) # 輸出: 2, 3, 4, 5, 6
for num in range(1, 10, 2):
print(num) # 輸出: 1, 3, 5, 7, 9
6. int(x)、float(x)、str(x)、bool(x) 等:將輸入值轉換為整數(shù)、浮點數(shù)、字符串或布爾值類型。
num1 = int("10")
num2 = float("3.14")
text = str(42)
flag = bool(1)
7. max(iterable)、min(iterable):返回可迭代對象中的最大值和最小值。
my_list = [3, 1, 5, 2, 4]
max_value = max(my_list)
min_value = min(my_list)
print(max_value) #輸出 5
print(min_value) #輸出 1
8. sum() 返回可迭代對象的和(用于數(shù)組類型的對象)
9. abs(x):返回數(shù)值的絕對值。
s = abs(-10)
print(s) #輸出 10
10. round(number, ndigits):將數(shù)值四舍五入到指定的小數(shù)位數(shù)
rounded_num = round(3.14159, 2)
print(rounded_num) #輸出3.14
11. dir() 函數(shù)不帶參數(shù)時,返回當前范圍內的變量、方法和定義的類型列表;帶參數(shù)時,返回參數(shù)的屬性、方法列表
>>>dir() # 獲得當前模塊的屬性列表
['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
>>> dir([ ]) # 查看列表的方法
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
?? 結合實戰(zhàn)練習
1. 列表中in和not in 的使用
some = [1,2,3,4,5,6]
print(3 in some) #輸出 True
print(3 not in some) #輸出 False
練習2 :讀取a.txt文件,對每一行使用split()方法拆分為單詞列表,對每一行單詞進行篩選去重復,添加到新的列表中。最后使用sort()進行排序。(大概意思是提取a.txt中出現(xiàn)過的單詞生成一個列表)
1. a.txt文件內容(請忽略內容是什么意思,網上是那個隨便找的)
Dear Sir/Madam,
I am writing this email to express my gratitude to you and to discuss
some matters. I hope this email finds you in good health and high
spirits.Firstly, I would like to sincerely thank you for your generosity and
assistance. I have been facing some difficulties in pursuing my career
goals, and your support has been invaluable to me. Your advice and
guidance have helped me gain a better understanding of the challenges
I have faced and have motivated me to continue striving.The purpose of this email is to request a meeting with you in order to
personally express my gratitude. I would like the opportunity to
showcase the progress I have made in my professional development and
to hear your valuable insights. If you are willing, I can arrange the
meeting according to your convenience, and the location and date can
be adjusted according to your preferences.Furthermore, I wanted to inquire if there is anything else I can do
for you. Your generosity may have an impact not only on me personally
but also on other individuals I may be able to assist. Please let me
know if there is anything you need help with, as I would be more than
happy to offer my assistance.Once again, thank you for your support and generosity, and I hold
great expectations for the future. I sincerely look forward to meeting
with you and expressing my gratitude in person. If you have any
questions or require further information regarding the meeting, please
feel free to contact me.With heartfelt appreciation,
[Your Name]
2. 提取單詞思路
遍歷文件每行內容
拆分每行內容為單詞列表
遍歷當前行列表單詞
查找list中是否存在當前單詞,存在記錄出現(xiàn)個數(shù),不存在新增一條記錄
3. 代碼:
th = open('a.txt')
print('讀取文件內容',th)
lst = list()#空列表
for item in th:
itemStr = item.rstrip()# 去除末尾空白符號
pList = itemStr.split()# 以空格作為分隔符分割每行數(shù)據(jù),返回一個單詞列表 ,例如首行:['Dear', 'Sir/Madam,']
for word in pList:
if len(lst)==0:
lst.append(word)
continue
if len(lst)>0:
if lst.count(word)>0:
continue
else:
lst.append(word)
print('列表長度',len(lst))
lst.sort()
print(lst)
4. 輸出結果
練習2 :讀取一份郵件,獲取到郵件中出現(xiàn)過的單詞生成字典,并記錄每個地址出現(xiàn)過的個數(shù)
1. a.txt內容和上一題一樣
2. 思路
讀取文件
聲明空字典
遍歷文件內容
去掉每行結尾空白符號
切割每行生成單詞字典
3. 代碼
th = open('a.txt')
dictStr = dict()#空字典
for item in th:
itemStr = item.rstrip()# 去除末尾空白符號
pDict = itemStr.split()# 以空格作為分隔符分割每行數(shù)據(jù),返回一個單詞列表 ,例如首行:['Dear', 'Sir/Madam,']
for word in pDict:
dictStr[word] = dictStr.get(word,0)+1 #查找。找到獲取對應值+1,沒找到默認為0+1
# print(dictStr.items())#items方法,返回可迭代對象的(key,value)
print(sorted([(k,v) for k,v in dictStr.items()]))
4. 運行結果
文章來源:http://www.zghlxwxcb.cn/news/detail-657913.html
練習3 :在練習2中升級,輸出練習2中,單詞出現(xiàn)最多的建和鍵值
bigKey = None #最大鍵
bigValue = None #最大鍵值
for k,v in dictStr.items():
if bigKey is None or v>bigValue: # is判斷是否相等,or或
bigValue = v
bigKey = k
print(bigKey,':',bigValue)
輸出結果:to : 17文章來源地址http://www.zghlxwxcb.cn/news/detail-657913.html
到了這里,關于python3 0基礎學習----數(shù)據(jù)結構(基礎+練習)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!