首页 > 解决方案 > 如何在python中使用和号对数学表达式进行排序

问题描述

如何对这样的数学表达式进行排序:

s = "1+3+2+1+4+3+5+16+63+3"

到所需的:

s = "1+1+2+3+3+3+4+5+16+63"

Python3

标签: pythonpython-3.x

解决方案


因为你的表达式是一个字符串。您首先需要从字符串中提取数字并对其进行操作:排序数字 -> 转换为字符串

>>> 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'

推荐阅读