Python入门到实践:day two

列表

一系列按照特定顺序排列的元素组成。
bicycles=["trek","cannondable","redline","specialized"]
print(bicycles)

  • 访问列表元素
bicycles=["trek","cannondable","redline","specialized"]
print(bicycles[0])#访问列表第一个元素
print(bicycles[0].title())
>trek
>Trek
  • 索引
    从0开始,而不是从1开始。
    例如"trek"的索引为0。
   print(bicycles[-1])#访问列表最后一个元素
   print(bicycles[-2])#访问列表倒数第二个元素
  • 使用列表中各个值
message="My first bicycle was a "+bicycles[0].title()+"."
print(message)
  • 修改,添加或删除列表元素
motorcycles=["honda","yamaha","suzuki"]
print(motorcycles)
motorcycles[0]='ducati'
print(motorcycles)
  • 在列表末尾添加元素
motorcycles=["honda","yamaha","suzuki"]
print(motorcycles)
motorcycles.append("ducati")#方法append()将元素添加到列表末尾
print(motorcycles)
  • 通过append()添加元素
motorcycles=[]
motorcycles.append("honda")
motorcycles.append("yamaha")
motorcycles.append("suzuki")
  • 在列表中插入元素
motorcycles=["honda","yamaha","suzuki"]
motorcycles.insert(0,"ducati")#方法insert(),指定插入元素值与索引位置
  • 从列表中删除元素
motorcycles=["honda","yamaha","suzuki"]
print(motorcycles)
del motorcycles[0]#del 删除指定索引位置的值
print(motorcycles)
popped_motorcycle=motorcycles.pop()#方法pop(),默认删除列表末尾的值,但任然可以访问
print(motorcycles)
print(popped_motorcycle)
motorcycles=["honda","yamaha","suzuki"]
first_owned=motorcycles.pop(0)#pop()方法可指定删除特定索引位置值
print("The first owned was a "+first_owned.title()+"!")
  • 根据值删除元素
motorcycles=["honda","yamaha","suzuki","ducati"]
too_expensive="ducati"
motorcycles.remove(too_expensive)#remove()方法根据元素值删除列表中元素
print(motorcycles)
print("\nA "+too_expensive.title()+" is too expensive for me!")
  • 组织列表
cars=["bmw","audi","toyota","subaru"]
cars.sort()#方法sort()永久性对列表进行排序
print(cars)

cars=["bmw","audi","toyota","subaru"]
cars.sort(reverse=True)#方法sort()永久性对列表进行排序,reverse=True,按照字母顺序相反方向排列
print(cars)
  • 暂时性对列表进行排序
cars=["bmw","audi","toyota","subaru"]
print("Here is the ordinary list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))#函数sorted()对列表进行临时排序
print("\nHere is the ordinary list again:")
print(cars)
  • 反转列表元素排列
cars=["bmw","audi","toyota","subaru"]
cars.reverse()#方法reverse()永久性反转列表元素
print(cars)
  • 确定列表长度
cars=["bmw","audi","toyota","subaru"]
len(cars)#函数len()获取列表长度,即列表元素数量
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值