山东大学Python(3)——容器

#%%
# 使用 jupyter notebook 编写
"""
本章知识目录:
    本节非常简单,看PPT即可,下面的代码为一些测试
"""

"""
考试:(非常重要)
查询、增加、删除、引用
PPT所有的都要看
"""

#%%

"""
list:
    list_name.append(x):在列表末尾位置添加元素x
    list_name.remove(x):删除首次出现的值为x的元素,x不存在则抛出异常
    del list_name[index]:删除索引为index的元素
    list_name.pop(index):删除索引为index的元素
    list_name.insert(index, x):在index处,添加x
    list_name.index(x):获取指定元素x首次出现的索引,不存在则抛出异常
    x in list_name:x在list_name中返回True,否则返回False
    x not in list_name:x不在list_name中返回True,否则返回False
    len(list_name):获取列表长度

dict:
    dict_name.fromkeys(list_name):以list_name为键创造值为None的字典
    del dict_name:删除整个字典
    dict_name.get(key):返回键为key的值,若不存在key,则创建该键值为None并返回None
    dict_name.get(key, value):返回键为key的值,若不存在key,则创建该键值为value并返回value
    key in dict_name:key在dict_name中返回True,否则返回False
    dict_name.has_key(key):含有key返回True,否则返回False
    dict_name.keys():以列表的形式返回所有的keys
    dict_name.values():以列表的形式返回所有的values
    dict_name.items():以列表的形式返回值为(key, value)的所有键值对
    dict_name1.update(dict_name2):将dict_name2添加到dict_name1中,若key相同,则覆盖
    del dict_name[key]:删除key所对应的元素
    dict_name.clear():清空字典中的所有键值对,使之成为空字典
    dict_name.pop(key):删除指定键并返回指定键的元素
    dict_name.popitem():随机删除一个键值对,并返回该键值对的值
"""

#%%

kobe_list = [2, '面向', False, 3.14, None]
print(kobe_list)
print(type(kobe_list))
kobe_list.append('end')
print(kobe_list)
kobe_list.remove(3.14)
print(kobe_list)
temp = kobe_list
del kobe_list[0]
print(kobe_list)
kobe_list = temp
print(kobe_list)
kobe_list.pop(-1)
print(kobe_list)
kobe_list.insert(-1, 'end')
print(kobe_list)
kobe_list.insert(0, 34)
print(kobe_list)
print(3 in kobe_list)

#%%

aList = [3, 4, 5, 6]
bList = ['A', 'B', 'C']
for a, b in zip(aList, bList):
    print(a, b)
print(type(zip(aList, bList)))
print(len(aList))

#%%

print(kobe_list)
print(kobe_list[1:4])
# PPT第15页的下面的图片,标着索引,看好-1和6的位置



#%%

atuple = ('first',)
print(type(atuple))
print(atuple)
btuple = ()
print(type(btuple))
ctuple = tuple()
print(type(ctuple))
print(tuple(aList))
print(aList)
del ctuple

#%%

azip = [1, 2, 3]
bzip = ['a', 'b', 'c', 'd']
czip = zip(azip, bzip)
print(czip)
print(list(czip))
tempzip = [(1, 'a'), (2, 'b')]
print(tempzip)
print(zip(tempzip))

#%%

adict = {3: 'c', 1: 'a', 2: 'b', 1: 'g'} # 后一个key为1的值'g'把前面的覆盖了
print(type(adict))
print(adict)
bdict = dict(czip)
print(dict(zip(aList, bList)))
cdict = dict(name=3, age='old')
print(cdict)
ddict = dict.fromkeys(['name', 'age', 'sex'])
print(ddict)
del ddict


发布了36 篇原创文章 · 获赞 20 · 访问量 2928

猜你喜欢

转载自blog.csdn.net/weixin_43360801/article/details/103317988