python的列表list的使用方法

1、什么是列表

列表是由一系列按特定顺序排列的元素,元素之间可以没有任何关系;可以创建空列表,也可以将任何东西添加进列表。

列表用 [ ] 表示:

cars = ['golf', 'magotan', 'sagitar', 'jetta']

2、列表序列是从0开始

1 cars = ['golf', 'magotan', 'sagitar', 'jetta']
2 print(cars[0])
3 golf
4 print(cars[2])
5 sagitar

3、首字母大写

1 cars = ['golf', 'magotan', 'sagitar', 'jetta']
2 print(cars[0].title())
3 Golf

4、遍历列表的方法

cars = ['golf', 'magotan', 'sagitar', 'jetta']
for i in cars:
    print(i)

 ⑵

cars = ['golf', 'magotan', 'sagitar', 'jetta']
length = len(cars)
i = 0
while i < length:
    print(cars[i])
    i+=1

5、append

添加元素,整体添加

cars = ['golf', 'magotan', 'sagitar', 'jetta']
tem = ['bora', 't-roc']
cars.append(tem)
print(cars) # ['golf', 'magotan', 'sagitar', 'jetta', ['bora', 't-roc']]

6、extend

添加元素,将另一个集合中的元素逐一添加到列表中

cars = ['golf', 'magotan', 'sagitar', 'jetta']
tem = ['bora', 't-roc']
cars.extend(tem)
print(cars) # ['golf', 'magotan', 'sagitar', 'jetta', 'bora', 't-roc']

7、insert

在指定index索引位置前插入元素

cars = ['golf', 'magotan', 'sagitar', 'jetta']
cars.insert(2, 'tayron')
print(cars) #['golf', 'magotan', 'tayron', 'sagitar', 'jetta']

8、修改元素

cars = ['golf', 'magotan', 'sagitar', 'jetta']
cars[0] = 'tayron'
print(cars) #  ['tayron', 'magotan', 'sagitar', 'jetta']

9、in(包含结果为true,不包含结果为false), not in(不包含结果为False,包含结果为True), index, count

cars = ['tayron', 'jetta', 'magotan', 'sagitar', 'jetta', 'bora', 't-roc']
love_car = 'tayron'
if love_car in cars:
  print('包含有')

# ------------------------
cars.index('jetta', 2, 4)
# jetta 在1和4的位置,所以报错 ''' Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> cars.index('jetta', 2, 4) ValueError: 'jetta' is not in list
'''
cars.count('bora')
# 5

10、删除元素del, pop, remove

del:根据下标进行删除

pop:删除最后一个元素

remove:根据元素的值进行删除

11、排序sort, reverse

sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。

reverse方法是将list逆置。

 

转载于:https://www.cnblogs.com/modys/p/10647574.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值