2025-12-24

9 阅读2分钟

今天学习了COLLOCATION IN USE里的student life单元的所有单词,并创建了每个单词的单词卡;另学习了列表。 #python基础

##列表定义

  • 由一系列按特定顺序排列的元素组成;
  • 由([])来表示,中间用逗号分隔:['a','b','c']
  1. 访问列表元素
  • 指出列表名词及索引(索引从0开始,每个索引是其逻辑位置-1,最后一个元素索引可以直接用-1代替,依次类推,你不需要准确数一共多少个) bicycles=['trek','cannondale','redline'] print(bicycles[0]) 》trek

  • 搭配其他方法处理元素:如title() print(bicycles[0].title()) 》Trek

  • 也可以直接使用列表里的值,结合之前的f字符串来创建信息: message=f“My first bicycle was a {bicycles[0].title()}." print(message) 》My first bicycle was a Trek.

  1. 修改列表元素
    • 赋值法,通过索引方式定位元素,再赋值
    • 在末尾追加:append (常见的用法是先创建空列表,再添加) motorcycles=['honda','yamaha','suzuki'] motorcycles.append('ducati') print(motorcycels)
  • 插入元素:insert(索引,值) motorcycles.insert(0,'ducati')
  • 删除元素:del(索引)--**该方法后你就无法访问该值了 del motorcycles[0]
  • 删除元素后还可以继续使用(针对非活动成员类似情形):pop()如果没有写明索引的话,则默认删除末尾元素 popped_moto=motorcycles.pop() print(motorcycels) print(popped_moto) print(f"The last motorcycles I owned was a {popped.title()}.") 》['honda','yamaha'] 》suzuki 》The last motorcycle I owned was a Suzuki.
  • 针对不知道要删除的元素的索引,只知道值,则可以使用remove(值),且可以继续使用该值 注意它只删除第一个特定的值。 motorcycles.remove('ducati') print(motorcycles)
  1. 使用sort()对列表进行永久排序 sort(reverse=False) 默认参数为False,代表按照字母表顺序排序,否则是相反

  2. 使用sorted()对列表进行临时排序list.sorted() or sorted(list) cars=['aa','cc','dd','bb'] 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: 》['aa','cc','dd','bb']

    》Here is the sorted list: 》['aa','bb','cc','dd']

    》Here is the original list again: 》['aa','cc','dd','bb']

  3. 反向打印列表:list.reverse(),按照现在的逻辑顺序做镜像**永久反向但可恢复""

  4. 确认列表长度:len(list)

``

dream_city=['paris','Newzed','tonkey','London'] print(dream_city) print(sorted(dream_city)) print(dream_city) dream_city.reverse() print(dream_city) dream_city.reverse() print(dream_city) dream_city.sort() print(dream_city) print(dream_city[0].title()) print(f"My favorite city is{dream_city[0]}") dream_city[3]="NewYork" dream_city.append("Tonkey") dream_city.insert(1,'Howayi') print(dream_city) del dream_city[2] print(dream_city) dl=dream_city.pop() print(dl) print(dream_city) dream_city.remove('Howayi') print(dream_city) dream_city.sort(reverse=True) print(dream_city) dream_city.reverse() print(sorted(dream_city)) print(dream_city) print(len(dream_city))