List
列表中可以存儲不同類型的數(shù)據(jù), 但在使用場景中,列表一般都存儲相同類型的數(shù)據(jù)
list1 = ['tom', 'jack', 'rose']
list1.index('jack') # 返回數(shù)據(jù)的索引
# 增加
list1.insert(1, 'json') # 從指定的位子插入
list1.append('json') # 從尾部添加
list2 = ['admin']
list1.extend(list2) # 將列表2追加到列表中
# 刪除
del list1[0] # 按索引從內(nèi)存中刪除
list1.remove('tom') # 刪除指定的元素。 第一次出現(xiàn)的數(shù)據(jù)
list1.pop() # 刪除最后一個元素
list1.pop(0) # 刪除指定的元素
list1.clear() # 清空列表
# 修改
list1[0] = 'json' # 指定索引修改
# 統(tǒng)計
len(list1) # 列表元素的長度: 3
list1.count('tom') # 數(shù)據(jù)在列表中出現(xiàn)的次數(shù)
# 排序
list1.sort() # 按字母升序排序
list1.sort(reverse=True) # 倒序
list1.reverse() # 按反轉(zhuǎn)列表
print(list1)
Tuple
與list 類似, 不同的是 元組的元素不能修改, 可以保護(hù)數(shù)據(jù)的安全
tuple = ('tom', 18, 17.5)
print(type(tuple)) # class 'tuple'
print(tuple[0]) # tom
print(tuple[1]) # 18
# 共2個方法
tuple = ('tom', 18, 17.5, 'tom')
print(tuple.index('tom')) # 第一次出現(xiàn)的數(shù)據(jù)的索引:0
print(tuple.count('tom')) # 出現(xiàn)的次數(shù): 2
print(len(tuple)) # 元素個數(shù)為:4
Dictionary
通常用于存儲描述一個物體的相關(guān)信息
dict = {"name":"jack"}
# 取值:如果鍵不存在就會報錯
print(dict['name']) # jack
# 增加: 不存在時
dict['age'] = 24
# 修改:存在時
dict['name'] = "tom"
# 刪除:如果鍵不存在就會報錯
dict.pop('name')
print(dict)
# 在實際開發(fā)中,由于字典中每一個鍵值對保存數(shù)據(jù)的類型是不同的,所以針對字典的循環(huán)遍歷需求并不是很多
for k in dict:
print("%s:%s" % (k, dict[k]))
# 主要方法
clear() get() pop() update()
copy() items() popitem() values()
fromkeys() keys() setdefault()
list(元組) 與 tuple(列表) 的轉(zhuǎn)換
num_list = [1, 2, 3, 4]
print(type(num_list)) # class 'list'
# list 轉(zhuǎn) tuple
num_tuple = tuple(num_list)
print(type(num_tuple)) # class 'tuple'
# tuple 轉(zhuǎn) list
num_list = list(num_tuple)
print(type(num_list)) # class 'list'