python基础之列表元组

python基础之列表元组

常用的数据类型

1、整数(int)
2、浮点数(float)
3、字符串(string)
4、布尔型(boolean)

列表和元组

1、列表特点
1-存放任意数据类型
2-属于可变对象,值可以修改

# 列表演示
testList1=[10,20,30,40,50]
testList2=['A','B','C']
testList3=['a',33,[10,20],{'A':'apple'},(1,2)]
print(f'''testList1:{testList1},
testList2:{testList2},
testList3:{testList3}''')
testList1[0]=98
print(testList1)
# 字符串属于不可变对象,不能修改其中值(错误演示)
strTest='abcde'
# strTest[0]='q'
# print(strTest)
# 修改testList3中[10,20]中数据
testList3[2][0]=96
print(testList3)

打印结果演示

testList1:[10, 20, 30, 40, 50],
testList2:['A', 'B', 'C'],
testList3:['a', 33, [10, 20], {'A': 'apple'}, (1, 2)]
[98, 20, 30, 40, 50]
['a', 33, [96, 20], {'A': 'apple'}, (1, 2)]

3-列表操作(增删改)

# 列表演示
testList1=[10,20,30,40,50]
testList2=['A','B','C']
testList3=['a',33,[10,20],{'A':'apple'},(1,2)]
print(f'''testList1:{testList1},
testList2:{testList2},
testList3:{testList3}''')
# 增加值到尾部 append
testList1.append(99)
print(testList1)
# 增加值到指定位置 insert
testList1.insert(1,36)#(x,y)x:下标位置 y:添加值
testList1.insert(999,666)# 超过列表最大下标 等同于 append
print(testList1)
# 列表拼接 extend
testList1.extend([33,99])
testList1.extend('abc')
print(testList1)
# 列表删除方式 pop
a=testList1.pop()#删除最后一位,用变量a接收
testList1.pop(1)#删除指定位置的值
print(a)
print(testList1)
# 列表删除方式 remove
testList1.remove(50)#根据值删除,效率低,当有多个相同的值时,只删除第一个
print(testList1)
# 列表删除方式 del
del testList1[0]
print(testList1)
#列表切片
print(testList1[0:2])
print(testList1)#不改变原列表
print(testList1[::-1])#翻转列表
#列表排序
testList4=[34,6,-1,90,102,87,99]
print(sorted(testList4))#临时排序
testList4.sort()#永久排序
testList4.sort(reverse=True)#倒序
print(testList4[::-1])
print(testList4)

打印结果演示

testList1:[10, 20, 30, 40, 50],
testList2:['A', 'B', 'C'],
testList3:['a', 33, [10, 20], {'A': 'apple'}, (1, 2)]
[10, 20, 30, 40, 50, 99]
[10, 36, 20, 30, 40, 50, 99, 666]
[10, 36, 20, 30, 40, 50, 99, 666, 33, 99, 'a', 'b', 'c']
c
[10, 20, 30, 40, 50, 99, 666, 33, 99, 'a', 'b']
[10, 20, 30, 40, 99, 666, 33, 99, 'a', 'b']
[20, 30, 40, 99, 666, 33, 99, 'a', 'b']
[20, 30]
[20, 30, 40, 99, 666, 33, 99, 'a', 'b']
['b', 'a', 99, 33, 666, 99, 40, 30, 20]
[-1, 6, 34, 87, 90, 99, 102]
[-1, 6, 34, 87, 90, 99, 102]
[102, 99, 90, 87, 34, 6, -1]

2、元组特点

#元组
testTuple1=(10,20,30,40,50)#元组是不可变对象,不能增/改/删元素,其他用法与列表一致
print(testTuple1[0:2])#可以使用下标或切片
testTuple2=(10,)
print(type(testTuple2))#用type()函数查看数据类型
testTuple3=(10,20,[30,40,50])
testTuple3[2][0]=900#可以修改元组中子列表的值
print(testTuple3)

打印结果演示

(10, 20)
<class 'tuple'>
(10, 20, [900, 40, 50])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值