Python 之列表

  • 列表简介
bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles)
# ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
# trek
print(bicycles[-1])
# specialized
  • 修改列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)

# ['honda', 'yamaha', 'suzuki']
# ['ducati', 'yamaha', 'suzuki']
  • 在列表中添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['honda', 'yamaha', 'suzuki', 'ducati']
  • 在列表中插入元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati') 
print(motorcycles)
# ['ducati', 'honda', 'yamaha', 'suzuki']
  • 从列表中删除元素
motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)
del motorcycles[0]
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['yamaha', 'suzuki']
  • 使用方法pop() 删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
# ['honda', 'yamaha', 'suzuki']
# ['honda', 'yamaha']
# suzuki
  • 弹出列表中任何位置处的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
# The first motorcycle I owned was a Honda.
  • 根据值删除元素
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
# ['honda', 'yamaha', 'suzuki', 'ducati']
# ['honda', 'yamaha', 'suzuki']
  • 使用方法sort() 对列表进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru'] 
cars.sort()
print(cars)
# ['audi', 'bmw', 'subaru', 'toyota']
cars.sort(reverse=True)
# ['toyota', 'subaru', 'bmw', 'audi']
  • 使用函数sorted() 对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:") 
print(cars)
print("\nHere is the sorted list:") 
print(sorted(cars))
print("\nHere is the original list again:") 
print(cars)


# Here is the original list:
# ['bmw', 'audi', 'toyota', 'subaru']
# Here is the sorted list:
# ['audi', 'bmw', 'subaru', 'toyota']
#  Here is the original list again: 
# ['bmw', 'audi', 'toyota', 'subaru']
  • 倒着打印列表
cars = ['bmw', 'audi', 'toyota', 'subaru'] 
print(cars)
cars.reverse() 
print(cars)

# ['bmw', 'audi', 'toyota', 'subaru']
# ['subaru', 'toyota', 'audi', 'bmw']
  • 确定列表的长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)
# 4
  • 遍历列表
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians:
    print(magician)
  • range
for value in range(1,6):
    print(value)
  • 创建数值列表
numbers = list(range(1,6))
print(numbers)
# [1, 2, 3, 4, 5]

even_numbers = list(range(2,11,2)) 
print(even_numbers)
# [2, 4, 6, 8, 10]
  • 列表复制
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。