[[列表]] []
[[元组]] ()
[[集合]] {}
[[字典]]{'':}
字典
# 创建字典的字面量语法
scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
print(scores)
# 创建字典的构造器语法
items1 = dict(one=1, two=2, three=3, four=4)
# 通过zip函数将两个序列压成字典
items2 = dict(zip(['a', 'b', 'c'], '123'))
# 创建字典的推导式语法
items3 = {num: num ** 2 for num in range(1, 10)}
print(items1, items2, items3)
# 通过键可以获取字典中对应的值
print(scores['骆昊'])
print(scores['狄仁杰'])
# 对字典中所有键值对进行遍历
for key in scores:
print(f'{key}: {scores[key]}')
# 更新字典中的元素
scores['白元芳'] = 65
scores['诸葛王朗'] = 71
scores.update(冷面=67, 方启鹤=85)
print(scores)
if '武则天' in scores:
print(scores['武则天'])
print(scores.get('武则天'))
# get方法也是通过键获取对应的值但是可以设置默认值
print(scores.get('武则天', 60))
# 删除字典中的元素
print(scores.popitem())
print(scores.popitem())
print(scores.pop('骆昊', 100))
# 清空字典
scores.clear()
print(scores)
列表
定义列表、如何遍历列表以及列表的下标运算
list1 = [1, 3, 5, 7, 100]
print(list1) # [1, 3, 5, 7, 100]
# 乘号表示列表元素的重复
list2 = ['hello'] * 3
print(list2) # ['hello', 'hello', 'hello']
# 计算列表长度(元素个数)
print(len(list1)) # 5
# 下标(索引)运算
print(list1[0]) # 1
print(list1[4]) # 100
# print(list1[5]) # IndexError: list index out of range
print(list1[-1]) # 100
print(list1[-3]) # 5
list1[2] = 300
print(list1) # [1, 3, 300, 7, 100]
# 通过循环用下标遍历列表元素
for index in range(len(list1)):
print(list1[index])
# 通过for循环遍历列表元素
for elem in list1:
print(elem)
# 通过enumerate函数处理列表之后再遍历可以同时获得元素索引和值
for index, elem in enumerate(list1):
print(index, elem)
切片
fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pitaya', 'pear', 'mango']
# 列表切片
fruits2 = fruits[1:4]
print(fruits2) # apple strawberry waxberry
# 可以通过完整切片操作来复制列表
fruits3 = fruits[:]
print(fruits3) # ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya', 'pear', 'mango']
fruits4 = fruits[-3:-1]
print(fruits4) # ['pitaya', 'pear']
# 可以通过反向切片操作来获得倒转后的列表的拷贝
fruits5 = fruits[::-1]
print(fruits5) # ['mango', 'pear', 'pitaya', 'waxberry', 'strawberry', 'apple', 'grape']
集合
创建集合
# 创建集合的字面量语法
set1 = {1, 2, 3, 3, 3, 2}
# 创建集合的构造器语法(面向对象部分会进行详细讲解)
set2 = set(range(1, 10))
set3 = set((1, 2, 3, 3, 2, 1))
# 创建集合的推导式语法(推导式也可以用于推导集合)
set4 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0}
增删元素
set1.add(4)
set1.add(5)
set2.update([11, 12])
set2.discard(5)
if 4 in set2:
set2.remove(4)
print(set1, set2)
print(set3.pop())
print(set3)
交集、并集、集差运算
# 集合的交集、并集、差集、对称差运算
print(set1 & set2)
# print(set1.intersection(set2))
print(set1 | set2)
# print(set1.union(set2))
print(set1 - set2)
# print(set1.difference(set2))
print(set1 ^ set2)
# print(set1.symmetric_difference(set2))
# 判断子集和超集
print(set2 <= set1)
# print(set2.issubset(set1))
print(set3 <= set1)
# print(set3.issubset(set1))
print(set1 >= set2)
# print(set1.issuperset(set2))
print(set1 >= set3)
# print(set1.issuperset(set3))
列表、元组、集合、字典、字符串转换之间的相互转换
本文由 简悦 SimpRead 转码, 原文地址 zhuanlan.zhihu.com
- 列表与元组的互换
# 将列表转化为元组
li = [1, 2, 3]
t = tuple(li)
print(t, type(t))
# 打印结果:(1, 2, 3) <class 'tuple'>
# 将元组转换成列表
tu = (1, 2, 3)
li = list(tu)
print(li, type(li))
# 打印结果:[1, 2, 3] <class 'list'>
- 列表与字符串的互换
# 列表转换成字符串
li = ['人', '生', '苦', '短']
str1 = ''.join(li)
print(str1, type(str1))
# 输出结果:人生苦短 <class 'str'>
# 字符串转换成列表
str2 = 'hello python'
li1 = str2.split(' ')
print(li1, type(li1))
# 输出结果:['hello', 'python'] <class 'list'>
- 列表与字典转换
# 列表转字典方式一
list1 = ['name', 'age', 'sex']
list2 = ['张三', 18, '男']
dict = {}
for i in range(len(list1)):
dict[list1[i]] = list2[i]
print(dict, type(dict))
# 输出结果:{'name': '张三', 'age': 18, 'sex': '男'} <class 'dict'>
# 列表转字典方式二:使用内置函数zip
list1 = ['name', 'age', 'sex']
list2 = ['张三', 18, '男']
d = dict(zip(list1, list2))
print(d)
# 字典转换成列表
dict = {'name': '张三', 'age': 18, 'sex': '男'}
keys = list(dict.keys())
values = list(dict.values())
print(keys, type(keys))
print(values, type(values))
- 嵌套列表转字典
list3 = [['key1','value1'],['key2','value2'],['key3','value3']]
print(dict(list3))
- 列表与集合转换
# 列表转集合
list1 = [1, 3, 4, 3, 2, 1]
s1 = set(list1)
print(s1, type(s1))
# 输出结果:{1, 2, 3, 4} <class 'set'>
# 集合转列表
list2 = list(s1.intersection(s1))
print(list2, type(list2))
# 输出结果:[1, 2, 3, 4] <class 'list'>
- 元组和字符串转换
# 元组转换成字符串和列表方法一样
# 字符串转换成元组,需要将字符串转换成列表,在利用列表转成元组
list = []
a = '人生苦短'
list.append(a)
print(list)
b = tuple(list)
print(b, type(b))
# 输出结果:('人生苦短',) <class 'tuple'>
- 元组和字典转换
# 字典转元组
dict = {'name': 'xiaoming', 'age': 18}
tup = tuple(dict)
print(tup) # 只转换了key
tup2 = tuple(dict.values())
print(tup2)
# 元组不能转成字典
- 字典和字符串转换
# 字典转换为字符串
dic1 = {'a': 1, 'b': 2}
str1 = str(dic1)
# 输出结果:{'a': 1, 'b': 2} <class 'str'>
# 字符串转字典
dic2 = eval("{'name':'xiaoming', 'age':18}")
print(dic2, type(dic2))
- 字符串和集合转换
# 字符串转集合
str1 = 'hello'
s1 = set(str1)
print(s1, type(s1))
# 输出结果:{'e', 'o', 'h', 'l'} <class 'set'>
- 字典 key 和 value 值转换
dic1 = {'a': 1, 'b': 2, 'c': 3}
dic2 = {value: key for key, value in dic1.items()}
print(dic2)