做笔记.记录生活中的点滴!

Python中数组 链表 元组 字典实现类Sql多字段排序和动态函数实现

上一篇 / 下一篇  2007-12-19 10:31:05 / 个人分类:编程技术

Python中数组排序及动态函数的实现


# -*- encoding: utf-8 -*-

"""
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)

TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-10-14  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 9866
  • 日志数: 19
  • 图片数: 1
  • 建立时间: 2006-12-16
  • 更新时间: 2008-02-21

RSS订阅

Open Toolbar