python 数据结构 容器(字典,列表,元组,集合)

# 列表
lt = [1, 2, 'hello', 3.14, True]

print(lt, type(lt))
# 通过下标获取元素,有越界问题
print(lt[1])#下标是从零开始的,下标为一,取出列表里面第二个元素
# 元组
tp = (1, 2, [3, 4, 5])
print(tp, type(tp))
# 也是通过下标进行访问
print(tp[2])
print(tp[2][0])#取出元祖里列表元素里面的第一个值
print(tp[2][0:])#取出元祖里列表元素里面的所有值

# 定义一个元素的元组后面要添加一个,
tp2 = (1,)
print(tp2, type(tp2))

# 集合:元素不能重复,并且是无序的
s1 = {'李白', '杜甫', '白居易', '王安石', '苏轼', '李白'}
s2 = {'李白', '李商隐', '李清照', '李贺', '李煜', '苏轼'}

print(s1, type(s1))
print(s2, type(s2))
# 交集
print(s1 & s2)
# 并集
print(s1 | s2)
# 差集
print(s1 - s2)
print(s2 - s1)

# 定义空集合不能使用{},这是留给定义空字典使用的
# 应该使用set()
# s3 = {}
# print(type(s3))
s4 = set()
print(type(s4))

# 字典
d = {'name': 'dahua', 'age': 18}#键值对形式,前面为健,后面为值,键必须唯一
print(d, type(d))
# 可以根据键获取值
print(d['name'])
# 当键不存在时或报KeyError错
# print(d['height'])
# 可以通过get方法根据键获取值,
print(d.get('age'))
# 当键不存在时不会报错,会返回None
print(d.get('height'))
# 可以设置默认值,有对应的键返回其值,没有时返回设置的默认值
print(d.get('weight', 75))

# 统计元素个数,字典统计的是键值对个数
print(len(d))
print(len(s1))
print(len(lt))
print(len('helloworld'))

原文地址:https://www.cnblogs.com/liangliangzz/p/10131124.html