python 根据规则进行数组排序

s=[('da2', u'da2 (600.1 GB)[slot(0, 3)]'), ('da0', u'da0 (2.0 TB)[slot(1, 1)]'), ('da1', u'da1 (2.0 TB)[slot(1, 2)]'), ('da3', u'da3 (2.0 TB)[slot(0, 2)]'), ('da5', u'da5 (2.0 TB)[slot(1, 3)]'), ('da16', u'da16 (2.0 TB)[slot(0, 1)]'), ('da17', u'da17 (2.0 TB)[slot(0, 0)]'), ('da18', u'da18 (2.0 TB)[slot(3, 2)]'), ('da19', u'da19 (2.0 TB)[slot(3, 1)]'), ('da20', u'da20 (2.0 TB)[slot(3, 0)]'), ('da21', u'da21 (2.0 TB)[slot(2, 0)]'), ('da22', u'da22 (2.0 TB)[slot(2, 1)]'), ('da23', u'da23 (2.0 TB)[slot(2, 2)]'), ('da24', u'da24 (15.5 GB)[slot(0, 0)]')]

根据slot(0,0)排序,结果是slot(0,0),slot(0,1)......

纯粹的[(0,1),(0,0),(2,2),(0,1)]这种我会,但是改成上述的就搞不定了╮(╯▽╰)╭

写个cmp函数就可以了

def t(x,y):    
    return cmp(x[1][-7:],y[1][-7:])
s.sort(cmp=t)
print s

追问

能详细下?小菜

追答

我也不知道怎么解释。。。cmp是提供了比较的规则,s通过调用cmp指定的函数来比较两个成员
这是sort函数在帮助文档,你看看吧
s.sort([cmp[, key[, reverse]]])
The sort() method takes optional arguments for controlling the
comparisons.

cmp specifies a custom comparison function of two arguments (list
items) which should return a negative, zero or positive number depending on
whether the first argument is considered smaller than, equal to, or larger than
the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The
default value is None.

key specifies a function of one argument that is used to extract a
comparison key from each list element: key=str.lower. The default value is None.

reverse is a boolean value. If set to True, then the list
elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are
much faster than specifying an equivalent cmp function. This is because
cmp is called multiple times for each list element while key
and reverse touch each element only once.

追问

恩,谢谢,能在问你个问题么
s这个列表,能对立面的内容进行填位么? 就是说 da1,da10,则在列表中,变成 da1空格,da10,这样就对齐了。。不知道我描述的能不能看懂╮(╯▽╰)╭
da10 slot
da1 slot
da11 slot

追答

你是要这个?

print "da1".ljust(4," ")+“slot”
print "da10".ljust(4," ")+“slot”

追问

是上述的列表s,把里面的 dax进行填充(da1改成da1+空格),而生成一个新的列表

追答def t(x,y):
    return cmp(x[1][-7:],y[1][-7:])
b=[(i[0].ljust(5,' '),i[0].ljust(5,' ')+re.sub('da\d+\s*','',i[1])) for i in s]
b.sort(cmp=t)
for i in b:
    print i

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答