python - 体重转换器

标签 python math list-comprehension

我正在使用 TDD 构建一个 Python 函数,该函数接受一串分隔的、递增的体重,例如 "103 123 4444 99 2000",并在同一字符串中输出相同的数字格式,但根据其各自的总和按升序排列。因此,上述输入的结果应为“2000 103 123 4444 99”

我已经设法将这些部分分解为根据输入破译正确顺序所需的部分,但是我不确定如何根据我设法计算的各个总和对输入重新排序。

您会注意到在第 5 行我使用了错误的整数,因为这些是总和,而不是原始输入。这只是我尝试可视化如何将列表转换回带有单个空格的字符串。

def ordered_weight(strng):
    str_split = strng.split()
    int_split = list(map(int, str_split))
    sum_lst = sorted([sum(map(int, str(i))) for i in str_split])
    return ' '.join(str(x) for x in sum_lst)

一位同事提出了一个附加参数:

When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9) it comes before as a string.

请帮忙!谢谢你! 乔丹

最佳答案

使用一个键函数返回数字和字符串本身的元组

def ordered_weights(s):
    spl = s.split()
    spl.sort(key=lambda x: (sum(map(int, x)), x))
    return ' '.join(spl)

对元组进行排序,如果第一个元素相等,则比较第二个元素,依此类推。

关于python - 体重转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40851534/

相关文章:

python - 无法从使用 Pandas 存储存档文件名称的 gzip 压缩文件中读取 csv 数据

python - 如何使用 WTForms 从模型列表创建表单?

c# - 如何通过将double转换为int来切断结尾?

Python - 展平字典列表

python - 在列表理解中使用 'while' 循环

python - Pandas excel 文件读取给出第一列名称为未命名

python - 清除Python中的线程?

javascript - Javascript 中的自定义轮数

c - 模乘法(C 语言)

python - 来自 pymongo 的游标列表理解