列表、元组和字典

列表、元组和字典

python内置常用的数据结构,列表和元组相似,它们都顺序保存元素,每个元素都有自己的索引,列表和元素通过索引来访问元素。区别元组不可修改,列表可以修改。字典是key-value形式保存数据。

3.1序列

序列指的是一种包含多项数据的数据结构,python的常见序列类型有:字符串、列表元组等。

3.1.1创建列表和元组

创建列表使用方括号,创建元组使用圆括号

# 使用方括号定义列表
my_list = ['crazyit', 20, 'Python']
print(my_list)
# 使用圆括号定义元组
my_tuple = ('crazyit', 20, 'Python')
print(my_tuple)

3.2列表和元组的通用法

列表和元组十分相似,它们包含多个元素,多个元素也有自己的索引。

3.2.1通过索引使用元素
a_tuple = ('crazyit', 20, 5.6, 'fkit', -17)
print(a_tuple)
# 访问第1个元素
print(a_tuple[0]) # crazyit
# 访问第2个元素
print(a_tuple[1]) # 20
# 访问倒数第1个元素
print(a_tuple[-1]) # -17
# 访问倒数第2个元素
print(a_tuple[-2]) # -fkit
3.2.2子序列

切片

a_tuple = ('crazyit', 20, 5.6, 'fkit', -17)
# 访问从第2个到倒数第4个(不包含)所有元素
print(a_tuple[1: 3]) # (20, 5.6)
# 访问从倒数第3个到倒数第1个(不包含)所有元素
print(a_tuple[-3: -1]) # (5.6, 'fkit')
# 访问从第2个到倒数第2个(不包含)所有元素
print(a_tuple[1: -2]) # (20, 5.6)
# 访问从倒数第3个到第5个(不包含)所有元素
print(a_tuple[-3: 4]) # (5.6, 'fkit')
#第一个包含第二个不包含
b_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
# 访问从第3个到第9个(不包含)、间隔为2的所有元素
print(b_tuple[2: 8: 2]) # (3, 5, 7)
# 访问从第3个到第9个(不包含)、间隔为3的所有元素
print(b_tuple[2: 8: 3]) # (3, 6)
# 访问从第3个到倒数第2个(不包含)、间隔为3的所有元素
print(b_tuple[2: -2: 2]) # (3, 5, 7)
3.2.3加法

列表和元组支持加法运算,加法的和就是两个列表或者元组的元素的和。

a_tuple = ('crazyit' , 20, -1.2)
b_tuple = (127, 'crazyit', 'fkit', 3.33)
# 计算元组相加
sum_tuple = a_tuple + b_tuple
print(sum_tuple) # ('crazyit', 20, -1.2, 127, 'crazyit', 'fkit', 3.33)
print(a_tuple) # a_tuple并没有改变
print(b_tuple) # b_tuple并没有改变
# 两个元组相加
print(a_tuple + (-20 , -30)) # ('crazyit', 20, -1.2, -20, -30)
# 下面代码报错:元组和列表不能直接相加
#print(a_tuple + [-20 , -30])
a_list = [20, 30, 50, 100]
b_list = ['a', 'b', 'c']
# 计算列表相加
sum_list = a_list + b_list
print(sum_list) # [20, 30, 50, 100, 'a', 'b', 'c']
print(a_list + ['fkit']) # [20, 30, 50, 100, 'fkit']
3.2.4乘法

列表和元组可以和整数执行乘法运算,乘的整数就是把它们所包含的元素重复整数次。

a_tuple = ('crazyit' , 20)
# 执行乘法
mul_tuple = a_tuple * 3
print(mul_tuple) # ('crazyit', 20, 'crazyit', 20, 'crazyit', 20)
a_list = [30, 'Python', 2]
mul_list = a_list * 3
print(mul_list) # [30, 'Python', 2, 30, 'Python', 2, 30, 'Python', 2]

可以使用加法和乘法运算。

# 同时对元组使用加法、乘法
order_endings = ('st', 'nd', 'rd')\
    + ('th',) * 17 + ('st', 'nd', 'rd')\
    + ('th',) * 7 + ('st',)
# 将会看到st、nd、rd、17个th、st、nd、rd、7个th、st
print(order_endings)
day = input("输入日期(1-31):")
# 将字符串转成整数
day_int = int(day)
print(day + order_endings[day_int - 1])

运算结果

('st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值