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

如何筛选列表中最后两个字符为“_N”的元素

筛选列表中以"_N"结尾的元素

你可以用两种简单的方式实现需求:

方法一:使用endswith()方法(推荐)

利用字符串内置的endswith()方法直接判断后缀,代码简洁直观:

aa = ["tea","tee","tea_N","tee_N"]
filtered_list = [item for item in aa if item.endswith("_N")]
print(filtered_list)  # 输出: ['tea_N', 'tee_N']

方法二:使用字符串切片判断

如果需要更灵活的子串判断,可以通过切片取最后两个字符进行对比,同时增加长度判断避免索引错误:

aa = ["tea","tee","tea_N","tee_N"]
filtered_list = [item for item in aa if len(item) >= 2 and item[-2:] == "_N"]
print(filtered_list)  # 输出: ['tea_N', 'tee_N']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:10:50