最近在學習Python,本文主要記錄在學習Python時關於數據結構的一些心得。python
# 列表 demo shopList = ['apple', 'mango', 'carrot', 'banana'] # len() 計算列表長度 print(len(shopList)) # 遍歷列表 for item in shopList: print(item, end=' ') # 追加元素 shopList.append('rice') print('My shopping list is now', shopList) # 排序 shopList.sort() print('My shopping list is now', shopList) # 刪除元素 del shopList[0] print('My shopping list is now', shopList) # 列表中插入元素 shopList.insert(1, 'red') print('My shopping list is now', shopList) # 列表尾部移除元素 shopList.pop() print('My shopping list is now', shopList)
Python中的列表相似於PHP中的數值數組
# 元組 demo zoo = ('python','elephant','penguin') # len() 計算長度 print(len(zoo)) # 訪問元組中的值 print(zoo[1])
元組和列表很是相似,可是元組初始化後值不能夠修改。
# 字典的demo ab = { 'Swaroop': 'swaroop@swaroopch.com', 'Larry': 'larry@wall.org', 'Matsumoto': 'matz@ruby-lang.org', 'Spammer': 'spammer@hotmail.com' } # 訪問字典中的元素 print(ab['Swaroop']) print(ab.get('Swaroop')) # 賦值 ab['test'] = 'test' print(ab) # 刪除元素 ab.pop('Larry') print(ab) del ab['Spammer'] print(ab) # 遍歷字典 for name, address in ab.items(): print('Contact {} at {}'.format(name, address))
Python中的字典相似於PHP的關聯數組
# 集合demo bri = set(['bra','rus','ind']) # 新增元素 bri.add('test') print(bri) # 移除元素 bri.remove('rus') print(bri) # 判斷元素是否存在集合中 print('bra' in bri)
以上列舉了Python中四大數據結構的簡單用法。若有錯誤,歡迎指正。git
趁着疫情期間,多學習學習~github
文章首發地址:https://tsmliyun.github.io/py...數組