代码之家  ›  专栏  ›  技术社区  ›  78282219

Python:排序数组返回非直观顺序

  •  0
  • 78282219  · 技术社区  · 7 年前

    Sorted_Array = ['Historic Rate', 'Overnight', '1M', '3M', '6M', '1Y', '2Y', '3Y', '4Y', '5Y', '6Y', '7Y', '8Y', '9Y', '10Y', '12Y', '15Y']
    
    Input = ['6M', '2Y', '7Y', '1Y']
    
    Output = ['7Y', '1Y', '6M', '2Y']
    

    输出是非直观的,应该是

    Actual_Output = ['6M','1Y','2Y','7Y']
    

    Ouput = [x for _, x in sorted(zip(Sorted_Array,Input), key=lambda pair: pair[0])]
    print(Output)
    

    有人能看出哪里出了问题吗?

    3 回复  |  直到 7 年前
        1
  •  2
  •   ikkuh    7 年前

    您当前正在对的项进行配对 Input Sorted_Array :

    >>> temp = list(zip(Sorted_Array, Input)))
    [('Historic Rate', '6M'), ('Overnight', '2Y'), ('1M', '7Y'), ('3M', '1Y')]
    

    >>> sorted(temp, key=lambda pair: pair[0])
    [('1M', '7Y'), ('3M', '1Y'), ('Historic Rate', '6M'), ('Overnight', '2Y')]
    

    现在应该很清楚你最终会得到什么样的结果。按元素的顺序排序 排序的\u数组 你能 index 功能:

    >>> sorted(Input, key=lambda item: Sorted_Array.index(item))
    ['6M', '1Y', '2Y', '7Y']
    

    注意:如果该项不在列表中,index函数将引发异常。

        2
  •  0
  •   deadvoid    7 年前

    sorted(zip(Sorted_Array,Input), key=lambda pair: pair[0]) 根据从中提取第二个成员的密钥(密钥对的第一个成员)对结果进行排序

    >>>> Output = [x for x in sorted(zip(Sorted_Array,Input), key=lambda pair: pair[0])]
    >>>> print(Output)
    [('1M', '7Y'), ('3M', '1Y'), ('Historic Rate', '6M'), ('Overnight', '2Y')]
    >>>> Output = [x for _, x in sorted(zip(Sorted_Array,Input), key=lambda pair: pair[0])]
    >>>> print(Output)
    ['7Y', '1Y', '6M', '2Y']
    

    pair[1]

    >>>> Output = [x for _, x in sorted(zip(Sorted_Array,Input), key=lambda pair: pair[1])]
    >>>> print(Output)
    ['1Y', '2Y', '6M', '7Y']
    
        3
  •  0
  •   Frayal    7 年前

    在python 2.x中:

    def dist(x,y):
         return sorted_array.index(x) - sorted_array.index(y)
    
    output = sorted(input, cmp=dist)
    

    在python 3.x中:

    def func(input):
        output = input
        for i in range(len(output)):
             try:
                output[i] = sorted_array.index(output[i])
             except Exception as e:
                output[i] = len(sorted_array)+1
        return output
    
    output = [ x for x,y in sorted((input,func(input),key = lambda k: k[1])]