[Python]《从入门到实践》第三章-列表简介

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
# 创建列表
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)

#访问元素
print(bicycles[0]) #访问第一个元素
print(bicycles[-1]) #-i 访问倒数第i个元素

#修改列表元素
bicycles[0] = 'ducati' 
print(bicycles)

#添加元素
bicycles.append('honda')  #在列表末尾添加元素
bicycles.insert(0,'yamaha') #在列表中添加元素

#从列表中删除元素
del bicycles[0]

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
popped_motorcycles = motorcycles.pop()
print(motorcycles)
print(popped_motorcycles)     #pop函数能在删除数之后使用它

motorcycles = ['honda','yamaha','suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycles I owned was a'+' '+first_owned.title()+'.')  #弹出列表中指定位置元素

motorcycles = ['honda','yamaha','suzuki']
motorcycles.remove('ducati') #根据值删除元素

motorcycles = ['honda','yamaha','suzuki']
too_expensive = 'honda'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA "+too_expensive.title()+" is too expensive for me.") #remove也可储存删除的的元素

#列表永久性排序
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)  #sort按字母顺序进行排序

#列表临时排序
print(sorted(cars))

#倒着打印列表
cars.reverse()
print(cars)

#确定列表长度
len(cars)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值