列表_list
可變的元素“集合”
- 創(chuàng)建列表:
name_list = ['bob', 'seven', 'eric'] 或 name_list = list(['alex', 'seven', 'eric'])
# 索引
print(name_list[0])
# 切片
print(name_list[0:2]) # 起始0,不包含2
# len
print(name_list[2:len(name_list)]) # len(name_list)恰起,判斷l(xiāng)ist長(zhǎng)度
# for
for i in name_list:
print(i)
# append,尾部追加
name_list.append('aaa')
# count,元素出現(xiàn)的次數(shù)
print(name_list.count('bob'))
# extend修械,擴(kuò)展,批量添加
temp= [11,22,33,44]
name_list.extend(temp)
# index,查看某個(gè)元素的索引
print(name_list.index('bob'))
# insert,向指定索引位置插入元素
name_list.insert(1,'tttttt')
print(name_list)
# pop,移除最后一個(gè)參數(shù)
name_list.pop()
# remove,移除特定參數(shù)
name_list.remove('bob')
# reverse,翻轉(zhuǎn)
name_list.reverse()
# del,根據(jù)索引刪除元素
del name_list[1]
元祖_tuple
幾乎跟列表是一樣的检盼,但是元組不能修改
創(chuàng)建元祖:
ages=(11,22,33,44,55) 或 ages=tuple((11,22,33,44,55))
# 索引
# 切片
# 循環(huán)
# 長(zhǎng)度
# 包含
# 不支持del刪除
# count,計(jì)算元素出現(xiàn)的個(gè)數(shù)
name_tuple.count('bob')
# index,獲取指定元素的索引位置
name_tuple.index('bob')
字典(無(wú)序)_dict
字典的每個(gè)元素都是一個(gè)鍵值對(duì)肯污,且無(wú)序
可理解為列表中的索引的0,1吨枉,2等數(shù)字可以靈活定義為其他的key
創(chuàng)建字典:
user_dict = { 'name':'bob', 'age':18,'gender':'M' } 或
user_dict =dict({ 'name':'bob',
'age':18,
'gender':'M' })
# 索引就是key
print(user_dict['name'])
# 循環(huán),默認(rèn)只輸出key
for i in user_dict:
print(i)
# 獲取所有key,并放到一個(gè)列表中
user_dict.keys()
# 獲取所有key,并放到一個(gè)列表中
user_dict.values()
# 獲取所有鍵值對(duì)(key和values),并放到一個(gè)列表中
user_dict.items()
# 循環(huán),默認(rèn)只輸出values
for i in user_dict.values():
print(i)
# clear,清除所有內(nèi)容
user_dict.clear()
# get,根據(jù)key獲取value,如果key不存在蹦渣,可以指定一個(gè)默認(rèn)值None
user_dict.get('age')
user_dict.get('aaaa') # 不存在,會(huì)返回None
user_dict.get('aaaa',333) # 不存在貌亭,返回默認(rèn)值333
# has_key,檢查字典中指定key是否存在——py3中已經(jīng)沒(méi)有了,用in代替
ret = 'age' in user_dict.keys()
# update,更新字典柬唯,之前的內(nèi)容刪除
test = {'a1':1,'a2':2}
user_dict.update(test)
print(user_dict)
# pop,獲取并在字典中移除
user_dict.pop('a1')
print(user_dict)
# popitem, 獲取并在字典中移除
user_dict.popitem()
print(user_dict)
# del,刪除指定索引的鍵值對(duì)
del test['a1']
print(test)
image.png