Python(六) 列表

Python 中没有数组,而是加入了功能更强大的列表(list),列表可以存储任何类型的数据。

使用

访问
a = [1,2.3,"python"]
print('a[0] -->', a[0])
print('a[1:] -->', a[1:])
输出
a[0] --> 1
a[1:] --> [2.3, 'python']
更新
a = [1,2.3,"python"]
a[1] = '更新'
print('a更新后--->',a)

#输出
a更新后---> [1, '更新', 'python']
'''
更新
还可以使用 append() 向列表中添加新元素
'''
a = [1,2.3,"python"]
a.append('hello')
print('a--->',a)

#输出
a---> [1, '2.3', 'python', 'hello']
删除
a = [1, 2.3, 'python', 'hello']
del a[2]
print('a--->',a)

#输出
a---> [1, 2.3, 'hello']
常用函数
len()列表元素个数

count()

统计列表中某个元素出现的次数

index()

查找某个元素在列表中首次出现的位置(即索引)

remove()

移除列表中某个值的首次匹配项

sort()

对列表中元素进行排序

copy()

复制列表
clear()清空列表
append()追加元素
l = ['d', 'b', 'a', 'f', 'd']
print(len(l))
print("l.count('d') -->", l.count('d'))

print("l.index('d') -->", l.index('d'))

l.remove('d')
print("l -->", l)

l.sort()
print('l -->', l)

lc = l.copy()
print('lc -->', lc)

lc.append('aaa')
print(lc)

lc.clear()
print('clear--->',lc)

#输出
5
l.count('d') --> 2
l.index('d') --> 0
l --> ['b', 'a', 'f', 'd']
l --> ['a', 'b', 'd', 'f']
lc --> ['a', 'b', 'd', 'f']
['a', 'b', 'd', 'f', 'aaa']
clear---> []

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值