Python学习笔记(3)-- 列表/元组/字典/集合操作

 


列表

mylist = ["a", "b", "c", "d", "e", "f", "g"]
# 元素获取
print(mylist[0])
# 元素更新
mylist[0] = "not a"
# 元素删除
del mylist[0]
# 列表遍历
for e in mylist:
    pass
# 判断元素是否在列表中
print("b" in mylist)
# 列表的切片操作
print(mylist[0::1])
print(mylist[::-1])     # 倒排
# 元素添加
mylist.append("h")              # 末尾添加
mylist.extend(["i", "j"])       # 合并其他列表
mylist = mylist + ["k", "l"]             # 列表合并
mylist.insert(3, "new element")     # 插入中间元素
print(mylist)
# 列表排序
num_list = [9, 2, 4, 6, 3]
num_list = sorted(num_list, reverse=True)
num_list.sort(reverse=False)
print(num_list)

列表的一些常用方法:

num_list = [9, 2, 4, 6, 3]
other_list = [3, 9, 10]
# 添加
num_list.append("new element")
num_list.extend(other_list)
num_list.insert(0, 100)
# 删除
num_list.remove(100)
num_list.pop(0)         # 参数是位置index,不是元素的值
num_list.clear()
# 倒序
num_list.reverse()
# 枚举遍历
num_list = [9, 2, 4, 6, 3]
for index, element in enumerate(num_list):
    print(index, element)

元组

my_tuple = (5, 2, 3, 4, 5)
print(my_tuple[2])
print(my_tuple.count(5))        # 统计元素的个数
print(max(my_tuple))            # 最大值
print(min(my_tuple))            # 最小值
print(sum(my_tuple))            # 求和

拆包和装包

my_tuple = (5, 2, 3, 4, 5)
a, *b, c = my_tuple
print(a, b, c)      # 5 [2, 3, 4] 5
print(a, *b, c)     # 5 2 3 4 5

*b包含中间任意个元素。


 

字典

my_dict = {"a": 1, "b": 2, "c": 3}
new_dict = dict([("a", 1), ("b", 2), ("c", 3)])
print(my_dict == new_dict)      # True
# 查询
print(my_dict["a"])
print(my_dict.get("b"))
# 添加
my_dict["d"] = 4
# 删除
del my_dict["d"]
value = my_dict.pop("c", "没有该值!")   # 弹出该key的元素,否则返回默认值
print("result:", value)
my_dict.clear()
# 遍历
for key in my_dict:
    print(key)

for key, value in my_dict.items():
    print(key, value)

# 两个字典修改
my_dict = {"a": 1, "b": 2, "c": 3}
new_dict = dict([("a", 1), ("b", 2), ("c", 4)])
my_dict.update(new_dict)
print(my_dict)

集合

my_set = {"a", "b", "c", "d"}
other_set = {"a", "e"}
# 添加
my_set.add("e")
my_set.update(other_set)    # 合并两个集合
# 遍历
for e in my_set:
    print(e)

# 删除
my_set.remove("a")  
my_set.discard("b")     # 删除指定元素,remove不存在会抛异常,discard不会
my_set.pop()            # 不能指定元素,弹出第一个元素
my_set.clear()

集合的交集、并集、差集和对称差集:

my_set = {"a", "b", "c", "d"}
other_set = {"a", "e"}
# 并集
new_set = my_set | other_set
new_set = my_set.union(other_set)
# 差集
new_set = my_set - other_set
new_set = my_set.difference(other_set)        # {'c', 'd', 'b'}

# 交集
new_set = my_set & other_set                    # {'a'}
new_set = my_set.intersection(other_set)

# 对称差集
new_set = (my_set | other_set) - (my_set & other_set)
new_set = my_set ^ other_set    # {'c', 'd', 'b', 'e'}

 

posted @ 2020-04-02 12:19  Epir  阅读(195)  评论(0编辑  收藏  举报