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

如何用仅含if else的列表推导式处理混合列表的字符串数字乘法

如何用if-else列表推导式处理混合类型列表:字符串数字乘2、保留指定元素

给定输入列表:

incoming_list = ['5', 6 , 3.5 , '6', 'g', '9']

期望输出:

['10', 6 , 3.5 , '12', 'g', '18']

实现思路

通过多层if-else的列表推导式,按以下优先级处理每个元素:

  1. 若元素是纯数字字符串:转整数乘2后转回字符串
  2. 若元素是奇数整数:执行求幂操作(你已完成的逻辑)
  3. 其余情况(浮点数、偶数整数、非数字字符串):直接保留原元素

完整代码

incoming_list = ['5', 6, 3.5, '6', 'g', '9']
result = [
    str(int(item) * 2) if isinstance(item, str) and item.isdigit()
    else item ** 2 if isinstance(item, int) and item % 2 != 0
    else item
    for item in incoming_list
]
print(result)

代码解释

  • 纯数字字符串判断:用isinstance(item, str)确认类型,再用item.isdigit()检查是否为纯数字(如果需要处理负数字符串,可调整为item.lstrip('-').isdigit())
  • 奇数整数处理:通过isinstance(item, int) and item % 2 != 0筛选奇数,执行求幂操作
  • 默认分支:自动覆盖浮点数、偶数整数、非数字字符串,直接保留原元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:15:33