Đây là điều tôi whipp ed lên (để giải quyết cùng một loại vấn đề). Tôi đã chỉ kiểm tra nó với các phiên bản mới nhất của Python cài đặt (OS X). Các bộ phận nhập khẩu dưới đây là những (clunkily tên) phím sắp xếp: sortKeyWithTwoListOrders và sortKeyWith2ndThen1stListValue
#Tested under Python 2.7.1 & Python 3.2.3:
import random # Just to shuffle for demo purposes
# Our two lists to sort
firstCol=['abc','ghi','jkl','mno','bcd','hjk']
secondCol=[5,4,2,1]
# Build 2 dimensional list [[firstCol,secondCol]...]
myList = []
for firstInd in range(0, len(firstCol)):
for secondInd in range(0, len(secondCol)):
myList = myList + [[firstCol[firstInd],secondCol[secondInd]]]
random.shuffle(myList)
print ("myList (shuffled):")
for i in range(0,len(myList)):
print (myList[i])
def sortKeyWithTwoListOrders(item):
return secondCol.index(item[1]), firstCol.index(item[0])
myList.sort(key=sortKeyWithTwoListOrders)
print ("myList (sorted according to strict list order, second column then first column):")
for i in range(0,len(myList)):
print (myList[i])
random.shuffle(myList)
print ("myList (shuffled again):")
for i in range(0,len(myList)):
print (myList[i])
def sortKeyWith2ndThen1stListValue(item):
return item[1], item[0]
myList.sort(key=sortKeyWith2ndThen1stListValue)
print ("myList (sorted according to *values*, second column then first column):")
for i in range(0,len(myList)):
print (myList[i])
myList (shuffled):
['ghi', 5]
['abc', 2]
['abc', 1]
['abc', 4]
['hjk', 5]
['bcd', 4]
['jkl', 5]
['jkl', 2]
['bcd', 1]
['ghi', 1]
['mno', 5]
['ghi', 2]
['hjk', 2]
['jkl', 4]
['mno', 4]
['bcd', 2]
['bcd', 5]
['ghi', 4]
['hjk', 4]
['mno', 2]
['abc', 5]
['mno', 1]
['hjk', 1]
['jkl', 1]
myList (sorted according to strict list order, second column then first column):
['abc', 5]
['ghi', 5]
['jkl', 5]
['mno', 5]
['bcd', 5]
['hjk', 5]
['abc', 4]
['ghi', 4]
['jkl', 4]
['mno', 4]
['bcd', 4]
['hjk', 4]
['abc', 2]
['ghi', 2]
['jkl', 2]
['mno', 2]
['bcd', 2]
['hjk', 2]
['abc', 1]
['ghi', 1]
['jkl', 1]
['mno', 1]
['bcd', 1]
['hjk', 1]
myList (shuffled again):
['hjk', 4]
['ghi', 1]
['abc', 5]
['bcd', 5]
['ghi', 4]
['mno', 1]
['jkl', 1]
['abc', 1]
['hjk', 1]
['jkl', 2]
['hjk', 5]
['mno', 2]
['jkl', 4]
['ghi', 5]
['bcd', 1]
['bcd', 2]
['jkl', 5]
['abc', 2]
['hjk', 2]
['abc', 4]
['mno', 4]
['mno', 5]
['bcd', 4]
['ghi', 2]
myList (sorted according to *values*, second column then first column):
['abc', 1]
['bcd', 1]
['ghi', 1]
['hjk', 1]
['jkl', 1]
['mno', 1]
['abc', 2]
['bcd', 2]
['ghi', 2]
['hjk', 2]
['jkl', 2]
['mno', 2]
['abc', 4]
['bcd', 4]
['ghi', 4]
['hjk', 4]
['jkl', 4]
['mno', 4]
['abc', 5]
['bcd', 5]
['ghi', 5]
['hjk', 5]
['jkl', 5]
['mno', 5]
bản sao có thể có của [Tiêu chí sắp xếp nâng cao cho danh sách các bộ dữ liệu lồng nhau] (http://stackoverflow.com/questions/3831449/advanced-sorting-criteria-for-a-list-of-nested-tuples) – SilentGhost