Python学习——列表的要点

什么是列表

在python 中用 [ ] 来表示列表,并用逗号来分隔其中元素:

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)

其次注意索引是 从0开始而不是从1

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles[0])

下面尝试使用列表中提取第一款汽车,并使用这个值来创建一条消息:

motorcycles = ['honda','yamaha','suzuki']
message = "My first motorcycle was a " + motorcycles[0].title() +"."
print(message)

如何修改 添加 删除元素

关于添加

使用 方法append() 添加元素:

>>> motorcycles = ['honda','yamaha','suzuki']
>>> motorcycles.append('ducati')
>>> print(motorcycles)

或者先创建一个空列表,再使用一系列append()语句添加元素:

>>> motorcycles = []
>>> motorcycles.append('honda')
>>> motorcycles.append('yamaha')
>>> motorcycles.append('suzuki')
>>> print(motorcycles)

关于插入

方法 insert() 可在列表的任何位置添加新元素:

>>> motorcycles = ['honda','yamaha','suzuki']
>>> motorcycles.insert(0,'ducati')
>>> print(motorcycles)

关于修改

注意第二行语句,利用索引重置定义:

>>> motorcycles = ['honda','yamaha','suzuki']
>>> motorcycles[0] = 'ducati'
>>> print(motorcycles)

关于删除

  1. 使用 del语句 删除元素:
>>> motorycles = ['honda','yamaha','suzuki']
>>> del motorcycles[0]
>>> print(motorcycles)
  1. 使用 方法pop() 删除元素:
>>> motorcycles = ['honda','yamaha','suzuki']
>>> popped_motorcycle = motorcycles.pop()
>>> print(motorcycles)

实际上,可以使用pop()来删除列表中任何位置的元素:

>>> motorcycles = ['honda','yamaha','suzuki']
>>> last_owned = motorcycles.pop(2)
>>> print("The last motorcycle I owned was a"+last_owned.title())
  1. 使用 方法remove() 来根据值删除元素:
>>> motorcycles = ['honda','yamaha','suzuki']
>>> too_expensive = 'yamaha'
>>> motorcycles.remove(too_expensive)
>>> print('A' + too_expensive.title() + 'is too expensive for me.')

注意要点:方法pop()和remove()的共同点在于:在列表中删除元素时,也可以直接使用它的值,与del语句的差别在于:如果要从列表中删除一个元素,那么这个元素以后不再使用。

组织列表

使用 方法sort() 对列表进行 永久性排序

>>> cars = ['bmw','audi','toyota','subaru']
>>> cars.sort()
>>> print(cars)

若需要与字母相反的顺序排序:

>>> cars = ['bmw','audi','toyota','subaru']
>>> cars.sort(reverse=ture)

使用 函数sorted() 对列表进行临时排序:

cars = ['bmw','audi','toyota','subaru']
print('Here is the sorted list:')
print(sorted(cars))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值