# coding=utf-8
import operator

def sortedTest():
    # list tuple 排序, key的参数是 for key in students
    students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
    print sorted(students, key=lambda student : student[2])   # sort by age
    print sorted(students, key=lambda student : student[2], reverse=True)   # sort by age

    # dict 排序 由于 for key in dict ,只会返回key，没有value,无法通过index获得key
    # 所以对于key 我们使用 iteritems(), for item in ages.iteritems() 返回的是键值对
    ages = {'john': 15, 'jane': 12, 'dave': 10}
    print sorted(ages.iteritems(), key=lambda ageItem : ageItem[1])
    # 等价于
    print sorted(ages.iteritems(),key=operator.itemgetter(1))

import random
def dictTest():
    keys = ['A', 'B', 'C']
    dic = {}
    for i in range(50):
        index = random.randint(0, 2)                # [0, 2]
        key = keys[index]
        dic[key] = dic.get(key, 0) + 1              # get(key, defaultValue) 获取value, 如果在树上没有找到key，默认为0

    print dic
dictTest()

def classAttrTest():
    testobj = dict()
    testobj["abc"] = 100
    if hasattr(testobj, "abc"): print "has abc"     # dict的属性在keys中不再dir出的对象属性中
    # setattr(testobj, "edf", 10)对于这种基本数据类型，不能添加属性
    for attr in dir(testobj):
        if attr[0] != "_":
            print attr, getattr(testobj,attr)

classAttrTest()

def frange(start, end, step):
    alist = []
    num = start
    while num <= end:
        alist.append(num)
        num += step
    return alist

# python extend 和 append是对原list操作，而返回none
def extend_append():
    a = [1,2,3]
    print a
    print a.append([1,2])
    print a
    print a.extend([1,2])
    print a

# 删除某个元素
def delete1(alist, index):
    del(alist[index])
    return alist

# 由于list是引用传递的，所以在写并行程序或递归程序时经常要求保留原list不变，而返回修改后的copy list
def delete2(alist, index):
    newlist = alist[:]      # 深拷贝
    del(newlist[index])
    return newlist

def delete3(alist, index):
    newlist = alist[:index]
    newlist.extend(alist[index+1:])
    return newlist

# 重新设置编码
import sys
def reloadCoding():
    reload(sys)
    sys.setdefaultencoding('utf-8')
reloadCoding()

# 测试函数属性的作用域
def testFuncAttri():
    def testfinvoke():
        print testf.a

    def testf():
        testf.a = 1
        print testf.a           # 该变量和函数同一个作用域
        testfinvoke()
    testf()
    print testf.a
testFuncAttri()