python - 如何在python中使用和号对数学表达式进行排序
问题描述
如何对这样的数学表达式进行排序:
s = "1+3+2+1+4+3+5+16+63+3"
到所需的:
s = "1+1+2+3+3+3+4+5+16+63"
在Python3
?
解决方案
因为你的表达式是一个字符串。您首先需要从字符串中提取数字并对其进行操作:排序数字 -> 转换为字符串
>>> s = "1+3+2+1+4+3+5+16+63+3"
>>> chars = s.split('+')
>>> numbers = list(map(int, chars))
>>> sorted_numbers = sorted(numbers)
>>> "+".join(list(map(str,sorted_numbers)))
'1+1+2+3+3+3+4+5+16+63'
推荐阅读
- python - 熊猫数据框返回无值
- sql - SUBSTRING 空值替代方案
- php - php中(bool)和(boolean)之间的区别?
- python - 如何在 Python 中为 EXR 文件将 float16 转换为 uint8
- fiware-cygnus - 如何从 Fiware Cygnus 获取数据?
- java - 将运算符添加到字符串返回值
- doctrine - 如何在 symfony 4 中获取关系数据库的 id?
- java - 在配置文件中使用 maven 复制和覆盖一些资源
- java - 无法将 JSON(类型字符串)转换为 ConcurrentHashMap
- c# - 使用 MicrosoftDNS 类 (ASP.net) 更新 DNS 服务器资源记录