【问题标题】:Sort List of Numbers according to Custom Number Sequence根据自定义编号顺序对编号列表进行排序
【发布时间】:2015-06-15 15:16:25
【问题描述】:

问题:
一组数字将作为输入传递。此外,按升序排列的数字 0-9 的重新定义关系将作为输入传递。根据重新定义的关系,这组数字必须按升序排列。

输入格式:
第一行将包含一组数字。 下一行将包含重新定义的升序排列的数字 0-9。

边界条件:
数字集的大小将从 2 到 100。

输出格式:
按照重新定义的数字顺序升序排列的一组数字,以空格分隔。

输入/输出示例 1:

输入:

20 50 11 121
9231476058

输出:

50 11 20 121

解释:

121 is a three digit number and hence comes first.
As per the redefined order 2 > 1 > 5.
So 121 is greater than all others and comes in the end.
20 > 11 > 50 and hence in ascending order this is reversed.

示例输入/输出 2:

输入:

319 311 198 420
1948327605

输出:

319 311 420 198

解释:

As per the redefined order 1 > 4 > 3
Among  319 and 311, 1 > 9
Hence the final ascending order is 319 311 420 198

我的解决方案:

if __name__ == '__main__':
    list_ = raw_input().split()
    num = str(raw_input())
    output = sorted(list_, key = num.index)
    print(' '.join(output))

我需要知道如何进行多级排序,以便比较第一个字符的索引,然后是第二个字符的索引,依此类推...

【问题讨论】:

    标签: list python-2.7 sorting


    【解决方案1】:

    这与您的输入/输出示例匹配,但我必须使用 降序 数字来获得示例答案。你确定你的解释是正确的吗?如果没有,只需在下面的代码中使用0123456789 而不是9876543210

    该算法是基于将数字的数字转换为其相应的排名数字提供排序键:

    import string
    
    def xsort(L,xlat):
        def xform(s):
            return int(str(s).translate(string.maketrans(xlat,'9876543210')))
        return sorted(L,key=xform)
    
    print xsort([20,50,11,121],'9231476058')
    print xsort([319,311,198,420],'1948327605')
    

    输出:

    [50, 11, 20, 121]
    [319, 311, 420, 198]
    

    参考:str.translatestring.maketrans

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2011-08-31
      • 1970-01-01
      • 2016-05-18
      相关资源
      最近更新 更多