标签:style 使用 os 文件 io for cti ar
列表解析
语法:[expr for iter_var in iterable] [expr for iter_var in iterable if cond_expr]
如果是有类的情况下,可以使用
class Person(object):
9 def __init__(self, name, age = 0):
10 self.name = name
11 self.age = age
12 def __repr__(self):
13 return ‘Name: %s\t‘\
14 ‘Age : %d‘ % (self.name, self.age)
def testListSort():
17 # 知识点:列表推导
18 persons = [Person(name) for name in (‘Shanno‘, ‘Tony‘, ‘Guass‘)]
例子:[类包(方法名t)for t in (obj1,obj2.....)]
生成器:(expr for iter_var in iterable)
(expr for iter_var in iterable if cond_expr)
Sorted语法
sorted(iterable, cmp=None, key=None, reverse=False)
operator.attrgetter的原型
operator.attrgetter(‘age‘)(sm_p)
for p in persons:
39 # 知识点:使用in判断key是否在dict内
40 if p.age not in persons_by_age:
41 persons_by_age[p.age] = [p]
42 else:
43 persons_by_age[p.age].append(p)
# 知识点:遍历dict获取的是key
46 for age in persons_by_age:
47 print ‘---------- age %d --------‘ % age
48 for p in persons_by_age[age]:
49 print p
50 print ‘\r\n‘
51
#知识点:defaultdict为不存在的key创建空的list
56 persons_by_age = collections.defaultdict(list)
57 for p in persons:
58 persons_by_age[p.age].append(p)
59
60 # 知识点:遍历dict获取的是key
61 for age in persons_by_age:
62 print ‘---------- age %d --------‘ % age
63 for p in persons_by_age[age]:
64 print p
对文件进行遍历
def getRelFilePathList(targetDir):
12 relFilePaths = []
13 for rt, dirs, files in os.walk(targetDir):
14 for fn in files:
15 fpath = os.path.join(rt, fn)
16 relFilePaths.append(os.path.relpath(fpath, targetDir))
17 return relFilePaths
18
标签:style 使用 os 文件 io for cti ar
原文地址:http://www.cnblogs.com/mhxy13867806343/p/3874610.html