【每日一题0820】按权重排序

:woman_mage:已知一个由纯数字组成的列表,请编写一个python函数,按照权重进行重新排序。权重的规则是:列表元素自身数字求和,按照和值依次从小到大进行排列。例如数字99和数字100,99的权重是9+9=18,100的权重是1+0+0=1,所以100应该排在99之前。
备注:如果两个数字的权重(和值)相同,则视为字符串,按照字母表顺序进行排序。

示例:
输入:[56,65,74,100,99,68,86,180,90] ,输出:[100,180,90,56,65,74,68,86,99]

题目难度:简单
题目来源:codewars

def order_by_weight(nums:list) -> list:
    pass

assert order_by_weight([56,65,74,100,99,68,86,180,90]) == [100,180,90,56,65,74,68,86,99]
assert order_by_weight([103,123,4444,99,2000]) == [2000,103,123,4444,99]
def order_by_weight(nums: list) -> list:
    weight = lambda x: sum([int(i) for i in list(str(x))])
    return sorted(nums, key=weight)

assert order_by_weight([56,65,74,100,99,68,86,180,90]) == [100,180,90,56,65,74,68,86,99]
assert order_by_weight([103,123,4444,99,2000]) == [2000,103,123,4444,99]  # 原来的断言缺少逗号分隔
def order_by_weight(nums: list) -> list:
    return sorted(nums, key=lambda i: sum(map(int, list(str(i)))))

assert order_by_weight([56, 65, 74, 100, 99, 68, 86, 180, 90]) == [100, 180, 90, 56, 65, 74, 68, 86, 99]
assert order_by_weight([103, 123, 4444, 99, 2000]) == [2000, 103, 123, 4444, 99]

为什么单独运行“lambda x: sum([int(i) for i in list(str(x))])”这个匿名函数是报错的,但是上述方法确可以使用的呢?

这个方法判断不了1和100的大小

public List<Integer> orderByWeight(List<Integer> list) {
        ArrayList<Integer> result = new ArrayList<>();
        Iterator<Integer> iterator = list.iterator();
        Map<Integer, Integer> map = new HashMap<>();
        // 获取位数之和
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            Integer next1 = next;
            int sum = 0;
            while (next != 0) {
                sum += next % 10;
                next /= 10;
            }
            map.put(next1, sum);
        }
        // 按value排序
        ArrayList<Map.Entry<Integer, Integer>> entries = new ArrayList<>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        // 获取排序后的数据
        for (Map.Entry<Integer, Integer> e : entries) {
            result.add(e.getKey());
        }
        return result;
    }
def order_by_weight(nums:list) -> list:
    weights = [(i, eval("+".join(list(str(nums[i])))), nums[i]) for i in range(0, len(nums)) ]
    weights.sort(key=lambda x:(x[1], str(x[2])))
    return [x[2] for x in weights]

    assert order_by_weight([56,65,74,100,99,68,86,180,90]) == [100,180,90,56,65,74,68,86,99]
    assert order_by_weight([103,123,4444,99,2000]) == [2000,103,123,4444,99]
关闭