Files
2026-08-22 01:09:23 +08:00

2.2 KiB
Raw Permalink Blame History

Day_4 · 列表:一串数据

预计耗时:20~30 分钟 列表就是一串排好队的数据。以后 ORM 查出来的"一堆结果",本质上就是一串对象。

今日知识点

  • 创建:fruits = ["apple", "banana"]
  • 增:fruits.append("orange") 尾部加;fruits.insert(0, "pear") 指定位置加
  • 删:fruits.remove("banana") 按值删
  • 查:fruits[0] 第一个、fruits[-1] 最后一个、len(fruits) 个数
  • 遍历:for f in fruits: print(f)

先学(教程)

任务(后做)

新建 day4.py,按顺序写并运行:

  1. 创建一个水果列表:
    fruits = ["apple", "banana"]
    print(fruits)
    
  2. 追加两个水果,删除一个,再打印:
    fruits.append("orange")
    fruits.append("grape")
    fruits.remove("banana")
    print(fruits)          # 现在有哪些?
    
  3. 遍历打印 + 长度:
    for f in fruits:
        print(f"我喜欢吃{f}")
    print(f"一共{len(fruits)}种水果")
    
  4. 打印第一个和最后一个:
    print(f"第一个:{fruits[0]}")
    print(f"最后一个:{fruits[-1]}")
    
  5. 进阶(加分):nums = [3, 1, 4, 1, 5],试试 nums.sort() 和 nums.reverse() 后分别打印。

完成标准

  • 四步输出都符合预期(增删改查 + 遍历)
  • 能说出 append 和 remove 的作用
  • (进阶)sort / reverse 结果正确

提交方式:把 day4.py 代码贴在当日工单评论里。

参考解答(先做再看)

fruits = ["apple", "banana"]
fruits.append("orange")
fruits.append("grape")
fruits.remove("banana")
print(fruits)              # ['apple', 'orange', 'grape']

for f in fruits:
    print(f"我喜欢吃{f}")
print(f"一共{len(fruits)}种水果")   # 一共3种水果

print(f"第一个:{fruits[0]}")       # apple
print(f"最后一个:{fruits[-1]}")    # grape

# 进阶
nums = [3, 1, 4, 1, 5]
nums.sort()
print(nums)                # [1, 1, 3, 4, 5]
nums.reverse()
print(nums)                # [5, 4, 3, 1, 1]