python编程从入门到实践

2017.5.3

2017-05-16  本文已影响1人  LorryZ

1. 访问列表元素 索引从0开始而不是1

bicycles = ['trek','cannondale','redline','specialized']

print(bicycles[0]) #返回第一个元素

print(bicycles[0].title())

print(bicycles[-1])  #返回最后一个元素 索引-2返回倒数第二个元素 以此类推

2. 修改列表元素 直接给索引值赋新的值

motorcycles = ['honda','yamaha','suzuki']

print(motorcycles)

motorcycles[0] = 'ducati'  #修改列表第一个元素的值

print(motorcycles)

3. 在列表末尾添加元素 使用append 不影响其他元素 可以先创建空列表 之后append其他元素

motorcycles = ['honda','yamaha','suzuki']

motorcycles.append('ducati')

print(motorcycles)

4. 使用insert在任意位置插入元素 需要写入插入的索引值

motorcycles = ['honda','yamaha','suzuki']

motorcycles.insert(1,'ducati')  #在索引1的位置插入新的元素

print(motorcycles)

motorcycles.insert(0,'honda1') #再在索引0的位置再插入一个元素

print(motorcycles)

5. 删除列表元素

motorcycles = ['honda','yamaha','suzuki']

motorcycles.insert(1,'ducati')

print(motorcycles)

motorcycles.insert(0,'honda1')

print(motorcycles)

del motorcycles[0]  #这里删除的是刚刚新加入的honda1

print(motorcycles)

6. 使用pop删除元素

motorcycles = ['honda','yamaha','suzuki']

popped_motorcycles = motorcycles.pop()  #删除最后一个元素

print(motorcycles)  

print(popped_motorcycles)

motorcycles = ['honda','yamaha','suzuki']

popped_motorcycles = motorcycles.pop(1) #也可以删除指定位置的元素

print(motorcycles)

print(popped_motorcycles)

如果删除一个元素,且不再以任何方式使用它,就使用del语句,如果在删除之后还需要使用该元素,则使用方法pop().

7. 使用sort对列表进行永久性排序

cars = ['bmw','audi','toyota','subaru']

cars.sort()  #正向排序

print(cars)

cars = ['bmw','audi','toyota','subaru']

cars.sort(reverse = True)  #逆向排序

print(cars)

print(sorted(cars)) #对列表进行临时的正向排序 也可以使用reverse=True来进行逆向排序

print(sorted(cars,reverse=True)) #需要把列表放在前面,reverse = True放在后面

print(cars) #打印之后结果还是刚才逆向排序的结果

cars.reverse()

print(cars) #reverse只是反转列表打印的顺序,不是像sort一样进行排序

#reverse也是永久性的,对列表进行两遍reverse跟原来列表相同

print(len(cars)) #打印cars的长度

上一篇 下一篇

猜你喜欢

热点阅读