python编程从入门到实践--第3章 列表简介

一。列表及使用

       列表相当于其它语言的可变数组,使用下标法引用,特殊之处可以用负数的下标引用尾部元素,-1最后一个元素,-2倒数第二个元素,依此类推。        

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)     # 打印整个数列表
print(bicycles[0])  # 访问元素
print(bicycles[-1].title())   # 访问最后一个元素
print(bicycles[-2].title())   # 访问倒数第二个元素

二。列表的修改、添加和删除元素  

# 修改元素值
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
motorcycles.append('honda')
print(motorcycles)

# 尾部添加元素--相当于入栈
names = []
names.append('Qingfeng Qian')
names.append('Bin Wang')
names.append('Cang Chen')
print(names)

#指定位置插入元素
names.insert(0, 'Kuo Zhang')
print(names)
names.insert(2, 'Mao Mao')
print(names)

#删除指定位置元素
del names[0]
print(names)

#弹出元素--删除末尾元素,相当于出栈
poped_name = names.pop()
print(names)
print(poped_name)


# 假定列表是以时间为序的
last_owned = motorcycles.pop()
print(f"The last motorcycle I owned waws a {last_owned.title()}")

# 弹出特定位置元素
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned waw a {first_owned.title()}")

# 按值删除元素
too_expensive = 'suzuki'
motorcycles.remove(too_expensive)
print(motorcycles)
print(f'\nA {too_expensive.title()} is too expensive for me.')

三。排序、反转与长度

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

# # 永久性排序
# cars.sort() # 默认升序
# print(cars)

# cars.sort(reverse=True)
# print(cars) #降序

# 临时排序
print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list agin:")
print(cars)

# 反转
print("\nHere is the reverse list:")
cars.reverse()
print(cars)

# 长度
print(len(cars))

 

posted @ 2022-10-10 15:05  獨懼  阅读(36)  评论(0)    收藏  举报