English 中文(简体)
以数量可变的钥匙分列的多层面清单
原标题:Sort a multidimensional list by a variable number of keys
  • 时间:2009-11-05 21:30:45
  •  标签:

页: 1

Edit:Immm 描述功能性功能与Excel......的分类功能一样,如果这样,它就会变得更清楚<>。

我在此局势下,有一份定点文件。 每一行约有125 000条线和6栏(栏目按表格分开)。 我将该文件分成两维名单。

我正试图撰写一份通用职务,以分类两维名单。 基本上,我要发挥我能通过大名单的职能,我想要把大名单打上一栏或多栏的关键。 显然,我要说的是,首先通过的关键是分类点,然后是第二个关键点。

仍然令人困惑?

在这方面,我要举一个例子说明我要做的事情。

Joel    18  Orange  1
Anna    17  Blue    2
Ryan    18  Green   3
Luke    16  Blue    1
Katy    13  Pink    5
Tyler   22  Blue    6
Bob     22  Blue    10
Garrett 24  Red 7
Ryan    18  Green   8
Leland  18  Yellow  9

我把这份名单传给我的神职:

sortByColumn(bigList, 0)

Anna    17  Blue    2
Bob     22  Blue    10
Garrett 24  Red 7
Joel    18  Orange  1
Katy    13  Pink    5
Leland  18  Yellow  9
Luke    16  Blue    1
Ryan    18  Green   3
Ryan    18  Green   8
Tyler   22  Blue    6

......

sortByColumn(bigList, 2, 3)

Luke    16  Blue    1
Anna    17  Blue    2
Tyler   22  Blue    6
Bob     22  Blue    10
Ryan    18  Green   3
Ryan    18  Green   8
Joel    18  Orange  1
Katy    13  Pink    5
Garrett 24  Red 7
Leland  18  Yellow  9

任何杂质?

最佳回答
import operator:
def sortByColumn(bigList, *args)
    bigList.sort(key=operator.itemgetter(*args)) # sorts the list in place
问题回答

第2栏和第3栏:

a.sort(key=operator.itemgetter(2,3))

The key idea here (pun intended) is to use a key function that returns a tuple. Below, the key function is lambda x: (x[idx] for idx in args) x is set to equal an element of aList -- that is, a row of data. It returns a tuple of values, not just one value. The sort() method sorts according to the first element of the list, then breaks ties with the second, and so on. See http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys

#!/usr/bin/env python
import csv
def sortByColumn(aList,*args):
    aList.sort(key=lambda x: (x[idx] for idx in args))
    return aList

filename= file.txt 
def convert_ints(astr):
    try:
        return int(astr)
    except ValueError:
        return astr    
biglist=[[convert_ints(elt) for elt in line]
         for line in csv.reader(open(filename, r ),delimiter= 	 )]

for row in sortByColumn(biglist,0):
    print row

for row in sortByColumn(biglist,2,3):
    print row

确保你将数字转换成斜体,否则,数字将按字母顺序排列,而不是按数字计算。

# Sort the list in place
def sortByColumn(A,*args):
    import operator
    A.sort(key=operator.itemgetter(*args))
    return A

# Leave the original list alone and return a new sorted one
def sortByColumn(A,*args):
    import opertator
    return sorted(A,key=operator.itemgetter(*args))




相关问题