问题:
一组数字将作为输入传递。此外,重新定义的数字 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))
我需要知道如何进行多级排序,以便比较第一个字符的索引,然后比较第二个字符等......
最佳答案
这与您的输入/输出示例相匹配,但我必须使用降序数字来获取示例答案。你确定你的解释是正确的吗?如果没有,只需在下面的代码中使用 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]
关于list - 根据自定义号码顺序对号码列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30848826/