PYTHON使用列表的一部分

1、切片

要创建切片,可指定要使用的第一个元素和最后一个元素索引

players=['charles','martina','michael','florence','eli']
print(players[0:3])

print(players[1:4])

print(players[:4])

print(players[2:])

print(players[-3:])

注意中间是冒号

没有起始索引,python从列表开头开始提取

没有终止索引,python一直提取到最后一个元素

起始索引若为-3,则提取最后三个元素

['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']

2、遍历切片

players=['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())

只遍历前三个

Here are the first three players on my team:
Charles
Martina
Michael

4、复制列表

要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引[:]

#复制列表
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]

#核实确实有两个列表
my_foods.append('cannoli')
friend_foods.append('ice cream')

print("My favourite foods are:")
print(my_foods)

print("\nMy friend's favourite foods are:")
print(friend_foods)

输出

My favourite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']

My friend's favourite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']

倘若我们只是简单地将my_foods赋值给friend_foods,就不能得到两个列表

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值