You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何完善Python水果存储程序及实现7种水果存储后的后续操作?

针对已存储7种水果的列表可执行的后续操作

先把你原来的代码调整为存储7种水果到列表的版本:

# 输入7种水果并存储到列表
fruits = [
    input("Name of 1st Fruit:  "),
    input("Name of 2nd Fruit:  "),
    input("Name of 3rd Fruit:  "),
    input("Name of 4th Fruit:  "),
    input("Name of 5th Fruit:  "),
    input("Name of 6th Fruit:  "),
    input("Name of 7th Fruit:  ")
]

完成输入存储后,你可以执行这些常见操作:

  • 查看列表内容:直接打印列表,或者遍历输出每个元素

    # 直接打印整个列表
    print(fruits)
    
    # 逐个打印更友好的格式
    for idx, fruit in enumerate(fruits, 1):
        print(f"{idx}th Fruit: {fruit}")
    
  • 修改列表元素:列表是可变类型,可修改指定位置的水果名称

    # 修改第3个水果的名称(索引从0开始,所以第3个对应索引2)
    fruits[2] = "Blueberry"
    
  • 添加新的水果:用append()在末尾加单个元素,或extend()批量添加

    # 添加单个水果
    fruits.append("Mango")
    
    # 批量添加多个水果
    fruits.extend(["Pineapple", "Watermelon"])
    
  • 删除列表元素:按索引删del、按值删remove(),或删末尾元素pop()

    # 删除第2个水果(索引1)
    del fruits[1]
    
    # 删除指定名称的水果(只删第一个匹配项)
    fruits.remove("Apple")
    
    # 删除并返回列表末尾的元素
    last_fruit = fruits.pop()
    
  • 排序列表:按字母顺序排序,可选择正序或倒序

    # 正序排序(直接修改原列表)
    fruits.sort()
    
    # 倒序排序
    fruits.sort(reverse=True)
    
    # 不修改原列表,返回排序后的新列表
    sorted_fruits = sorted(fruits)
    
  • 统计元素相关信息:比如统计某个水果出现的次数,获取列表长度

    # 统计列表长度(当前有多少种水果)
    print(f"总共有 {len(fruits)} 种水果")
    
    # 统计特定水果出现的次数
    print(f"Apple出现了 {fruits.count('Apple')} 次")
    
  • 查找元素索引:获取某个水果在列表中的位置

    # 获取第一个匹配项的索引
    if "Banana" in fruits:
        index = fruits.index("Banana")
        print(f"Banana在列表中的位置是第 {index+1} 位")
    

内容的提问来源于stack exchange,提问作者Harpreet Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:10:27