# coding=utf-8 __author__ = 'liuyb' ######### # tuple # ######### # 元组 def fuc_tuple(): # 元组定义 t = 12345, 54321, "hello" print t # 元组是可嵌套的 u = t, (1, 2, 3, 4, 5) print u # 元组是不可变的 # t[0] = 888 # 单元元组可以包含可变对象 v = ([1, 2, 3], [3, 2, 1]) print v print v[0] # 元组的长度 print len(t) # list和tuple区别 t = "hello" t1 = "hello", print t print t1 # 定义 x, y, z = t ######## # sets # ######## # 集,无序,无重复 # sets 标准操作 def fuc_sets_stander(): a = set('abracadabra') b = set('alacazam') print a print b # 求差集 print a - b # 并集 print a | b # 交集 print a & b # 对称差集(元素在a或b中,但不会同时出现在二者之间) print a ^ b def fuc_sets_operate(): a = set('abracadabra') b = set('alacazam') a.add("x") print a a.update(["1", "2", "3"]) print a a.remove("1") print a print "len of a is :", len(a) print "'3' in a is:", "3" in a ######## # 字典 # ######## def fuc_dict_stander(): person = {"name":"pony", "sex":"man"} person["age"] = "20" print person print person["name"] del person["sex"] print person print person.keys() print "name" in person # list转字典 def fuc_dict_list(): return dict([("name","bob"), ("sex", "man")]) # tuple转字典 def fuc_dict_tuple(): return dict(sape = 1234, guido = 2345, jack = 3456) # 字典解析 def fuc_dict_for(): return {x : x**2 for x in range(2, 7, 2)} ########### # 循环技术 # ########### # enumerate() 获取索引和对应的值 def fuc_enumerate(): for k , v in enumerate(["tic", "tac", "tbc"]): print k , v # iteritems() 获取字典的索引和对应的值 def fuc_iteritems(): knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.iteritems(): print k, v # zip() 同事遍历两个或以上的参数列表 def fuc_zip(): questions = ['name', 'quest', 'favorite color'] answers = ['TOM', 'the holy grail', 'blue'] for q, a in zip(questions, answers): print "what is your {0}? It is {1}." .format(q, a) # reversed() 取相反的序列 def fuc_reversed(): for i in reversed(xrange(1, 10 , 2)): print i # sorted() 序列排序,从小到大 def fuc_sorted(): basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for f in sorted(set(basket)): print f # sorted(reverse = True) 顺序排列,从大到小 def fuc_sorted_reverse(): basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for f in sorted(set(basket),reverse=True): print f if __name__=="__main__": print fuc_iteritems()
2.3 数据结构-数据类型
最新推荐文章于 2021-12-16 17:18:06 发布