Python中数组排序及动态函数的实现
"""
Python中实现多维数组(元组)排序:
下面是我写的一个小例,实现类似于SQL的多字段排序
sorted函数参考如下:
sorted( iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable. The optional
arguments cmp, key, and reverse have the same meaning as those for the
list.sort() method. New in version 2.4.
"""
a = (
(120,250,780,567,234,6789),
(120,234,560,256,555,5674),
(789,250,634,894,456,1200),
(695,250,432,356,654,686)
)
b = sorted(a,cmp=lambda x,y:cmp(x[0],y[0]) or cmp(x[1],y[1]) or cmp(x[2],y[2]))
print a
print b
""" 一般排序 """
""" 顺序: """
c = [5, 2, 3, 1, 4]
c.sort()
print c
"""倒序1:"""
c = [5, 2, 3, 1, 4]
c.sort(cmp=lambda x,y: y-x)
print c
"""倒序2: """
c = [5, 2, 3, 1, 4]
c.sort(reverse=True)
print c
"""倒序3:"""
c = [5, 2, 3, 1, 4]
c.sort()
print c
c.reverse()
print c
print sorted(c,reverse=True)
""" 字典排序 """
mydict ={"abc":125,
"bcd":215,
"ddd":333,
"dgf":214
}
"""从2.4 开始数组的排序可以指定键位置!"""
for k, v in sorted(mydict.items()
, key=lambda x: x[1]
,reverse=True):
print k,v
""" 动态函数的实现 """
func = """def foo():
a = 'hello world'
print a"""
exec func
print type(foo)
"""单句动态函数实现"""
exec 'def test_fun(): pass'
print type(test_fun