2011-06-10Python

没有评论
68

Python 列表(list)和字典(dict)数据排序

分类:Python

  1. # 这个类用来演示如何对自定义对象进行排序
  2. class Sortobj:
  3.     a = 0
  4.     b = ''
  5.     def __init__(self, a, b):
  6.         self.a = a
  7.         self.b = b
  8.     def printab(self):
  9.         print self.a, self.b
  10.   
  11. # 演示对字符串列表进行排序
  12. samplelist_str = ['blue','allen','sophia','keen']
  13. print samplelist_str
  14. samplelist_str.sort()
  15. print samplelist_str

继续阅读 »

Python 中两个字典(dict)合并

分类:Python

  1. dict1={1:[1,11,111],2:[2,22,222]}
  2.     dict2={3:[3,33,333],4:[4,44,444]}

合并两个字典得到类似

  1. {1:[1,11,111],2:[2,22,222],3:[3,33,333],4:[4,44,444]}

方法1:

  1. dictMerged1=dict(dict1.items()+dict2.items())

方法2:

  1. dictMerged2=dict(dict1, **dict2)

方法2等同于:

  1. dictMerged=dict1.copy()
  2.     dictMerged.update(dict2)

继续阅读 »

Python 动态加载模块的3种方法

分类:Python1,使用系统函数__import_()

  1. stringmodule = __import__('string')

2,使用imp 模块

  1. import imp
  2. stringmodule = imp.load_module('string',*imp.find_module('string'))

3,使用exec

  1. import_string = "import string as stringmodule"
  2. exec import_string

变量是否存在

  1. 1,hasattr(Test,'t')
  2. 2, 'var'   in   locals().keys()
  3. 3,'var'   in   dir()
  4. 4,vars().has_key('s')

返回顶部