2015-09-28 25 views
1

Alphabet Data List如何使用Python3中的兩個條件對對象進行排序?

  • 字母表中的列表表示對象。
  • 每個字母都有一箇中心座標(x,y)。
  • 該數字表示其列表中的索引。

我想按照[A,B,C,D]的順序排列項目。所以...

if abs(A.y - B.y) < threshold: 
    # sort by x coordinate 
else: 
    # sort by y coordinate 

我可以通過手動檢查對象並直接交換它們的位置來做到這一點。

但我該怎麼用Python3​​函數做這個?

回答

4

寫一個比較函數,然後用functools.cmp_to_key把它轉換成一個關鍵功能:

# Given a threshold, return a function suitable for 
# use by old cmp argument 
def comparator(threshold): 
    def compare(A, B): 
     if abs(A.y - B.y) < threshold: 
      return cmp(A.x, B.x) 
     else: 
      return cmp(A.y, B.y) 
    return compare 

from functools import cmp_to_key 
my_cmp = comparator(0.6) # Or whatever threshold you need 
sorted_list = sorted(my_list, key=cmp_to_key(my_cmp)) 
+0

打我幾秒:-) –

-1
sorted(your_list, key=lambda p: (p.x, p.y)) 
+0

這沒有考慮到'y'座標差異的閾值。 – chepner

3

按照python3文檔:Sorting How To你會定義一個複雜的比較功能,然後用functools。 cmp_to_key將其轉換爲一個關鍵的功能:

這應該工作:

import functools 
def comp_func(A,B): 
    if abs(A.y - B.y) < threshold: 
     return A.y - B.y # Sort by y co-ord 
    else: 
     return A.x - B.x # Sort by x co-ord 

.... 
sorted(data, key=functools.cmp_to_key(comp_func)) 
相關問題