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

Python打印列表前如何移除元素中的'- Flower'与'- Shrub'后缀

问题描述

现有Python代码逻辑为遍历存储植物条目信息的data列表,将包含- Flower的条目归入flowers列表,其余条目归入shrubs列表后直接打印两个列表。需要调整代码:打印前移除所有条目中的- Flower、- Shrub后缀,仅保留纯植物名称再输出。

原代码如下:

data = [
    "Andromeda - Shrub",
    "Bellflower - Flower",
    "China Pink - Flower",
    "Daffodil - Flower",
    "Evening Primrose - Flower",
    "French Marigold - Flower",
    "Hydrangea - Shrub",
    "Iris - Flower",
    "Japanese Camellia - Shrub",
    "Lavender - Shrub",
    "Lilac - Shrub",
    "Magnolia - Shrub",
    "Peony - Shrub",
    "Queen Anne's Lace - Flower",
    "Red Hot Poker - Flower",
    "Snapdragon - Flower",
    "Sunflower - Flower",
    "Tiger Lily - Flower",
    "Witch Hazel - Shrub",
]

flowers = []
shrubs = []

for plant in data:
    if "- Flower" in plant:
        flowers.append(plant)
    else:
        shrubs.append(plant)
print(flowers)
print(shrubs)
解决方案

不需要先存完整带后缀的字符串再二次遍历处理,在分类追加元素到对应列表时,直接把后缀切掉即可。

  • 推荐用字符串拆分的方式实现,按固定分隔符-拆分后取第一段内容就是纯植物名,全Python版本兼容,还能简化分支逻辑
  • 如果运行环境是Python 3.9及以上,也可以用自带的str.removesuffix()方法,精准移除末尾指定后缀,语义更直观

修改后的可运行代码:

data = [
    "Andromeda - Shrub",
    "Bellflower - Flower",
    "China Pink - Flower",
    "Daffodil - Flower",
    "Evening Primrose - Flower",
    "French Marigold - Flower",
    "Hydrangea - Shrub",
    "Iris - Flower",
    "Japanese Camellia - Shrub",
    "Lavender - Shrub",
    "Lilac - Shrub",
    "Magnolia - Shrub",
    "Peony - Shrub",
    "Queen Anne's Lace - Flower",
    "Red Hot Poker - Flower",
    "Snapdragon - Flower",
    "Sunflower - Flower",
    "Tiger Lily - Flower",
    "Witch Hazel - Shrub",
]

flowers = []
shrubs = []

for plant in data:
    # 按固定分隔符拆分,直接提取纯植物名
    plant_name = plant.split(" - ")[0]
    if " - Flower" in plant:
        flowers.append(plant_name)
    else:
        shrubs.append(plant_name)

print(flowers)
print(shrubs)

运行输出结果:

['Bellflower', 'China Pink', 'Daffodil', 'Evening Primrose', 'French Marigold', 'Iris', "Queen Anne's Lace", 'Red Hot Poker', 'Snapdragon', 'Sunflower', 'Tiger Lily']
['Andromeda', 'Hydrangea', 'Japanese Camellia', 'Lavender', 'Lilac', 'Magnolia', 'Peony', 'Witch Hazel']

Python 3.9+版本可以替换为后缀移除的写法,可读性更高:

for plant in data:
    if "- Flower" in plant:
        flowers.append(plant.removesuffix(" - Flower"))
    else:
        shrubs.append(plant.removesuffix(" - Shrub"))

内容的提问来源于stack exchange,提问作者Shiloh Izuchukwu Anigbogu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:06:19