python笔记:列表

文章介绍了Python中列表的基本操作,包括索引、修改(如修改元素值、插入和删除),以及常用的列表方法如append、extend、insert、pop、remove、clear、count和计算列表长度。
摘要由CSDN通过智能技术生成
my_list = ['hello', 666, True]
列表中的元素的类型不受限制,这点和数组不一样(也即是说列表里面还可以套个列表,be like:

my_list2 = [my_list, '123', 23, [1, 2, 3]]

my_list = [1, 2, 3, True, 'helloworld']
my_list2 = [my_list, 1]
print(my_list2)

# 打印:[[1, 2, 3, True, 'helloworld'], 1]

列表可以正向索引(第一个元素index为0)也可以反向索引(最后一个元素index为-1,向前以此递减1)

对于嵌套list,类似二维数组

列表的方法:

(为什么叫方法?:定义在类内的成员函数,就叫方法,list也是个类嘛,定义在list类内的一系列函数就叫方法

方法和函数功能一样,只是方法的使用格式不同

函数的使用:num = add(1,2)

方法的使用:student = Student()

                        num = student.add(1, 2)

list.append(元素)
list.extend(元素)
list.insert(下标,元素)
del list[下标]
list.pop(下标)
list.remove(元素)
list.clear()
list.count(元素)
list.index(元素)
len(列表)

 

 

1. index查询:
my_list = [1, 2, 3, True, 'helloworld', True]
print(my_list.index(True))
# 打印:0
2.修改
my_list = [1, 2, 3, True, 'helloworld', True]
my_list[0] = 5
print(my_list)
# 打印:[5, 2, 3, True, 'helloworld', True]
3.insert插入

语法:列表.insert(下标,元素),在指定的下标位置,插入指定的元素

my_list = [1, 2, 3, True, 'helloworld', True]
my_list.insert(1, 5)
print(my_list)
# 打印:[1, 5, 2, 3, True, 'helloworld', True]
4.append追加,追加单个元素

在尾部追加,而不是指定位置

my_list = [1, 2, 3, True, 'helloworld', True]
my_list.append(7)
print(my_list)
# 打印:[1, 2, 3, True, 'helloworld', True, 7]
5.extend追加,追加一批

语法:列表.extend(其他数据容器),将其他数据容器的内容取出(不是物理意义上的“取出”哈,是一种复制),依次追加到列表尾部

my_list = [1, 2, 3, True, 'helloworld', True]
my_list2 = [4, 5, 6]
my_list.extend(my_list2)
print(my_list)
# 打印:[1, 2, 3, True, 'helloworld', True, 4, 5, 6]
6.删除

del:

my_list = [1, 2, 3, True, 'helloworld', True]
del my_list[2]
print(my_list)
# 打印:[1, 2, True, 'helloworld', True]

pop:

my_list = [1, 2, 3, True, 'helloworld', True]
element = my_list.pop(2)
# 可以拿个变量接收一下,本质上是把下标为2的元素取出来再返回
print(my_list)
# 打印:[1, 2, True, 'helloworld', True]

remove:删除某元素在列表中的第一个匹配项

语法:列表.remove(元素)

my_list = [1, 2, 3, True, 'helloworld', True]
my_list.remove(2)
print(my_list)
# 打印:[1, 3, True, 'helloworld', True]
7.clear清空

语法:列表.clear()

8.count统计某元素在列表内的数量

语法:列表.count(元素)

my_list = [1, 2, 3, True, 'helloworld', True]
element = my_list.count(True)
print(element)
# 打印:3
# 原来python认为1也是True啊!神奇
9.统计列表中全部的元素数量

语法:len(列表)

my_list = [1, 2, 3, True, 'helloworld', True]
count = len(my_list)
print(count)
# 打印:6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值