标签:abc 列表 ted condition sequence 就会 元组 删除 cond
#序列解包 >>> x,y,z = 1,2,3 >>> print(x,y,z) 1 2 3 >>> dic = {‘Jameson‘:‘1001‘,‘Jack‘:‘1002‘,‘Abel‘:‘1003‘} >>> key,val = dic.popitem() >>> print(key,val) Jack 1002 #链式赋值 >>> a = b = c = 3 >>> print(a,b,c) 3 3 3 #增量赋值 >>> str2 = "abc" >>> str2 += "def" >>> str2 ‘abcdef‘ >>> str2 *= 3 >>> str2 ‘abcdefabcdefabcdef‘
#if,elif,else if condition_1: statement_block_1 elif condition_2: statement_block_2 else: statement_block_3 #比较运算符 """ x == y x等于y x < y x小于y x > y x大于y x >= y x大于等于y x <= y x小于等于y x != y x不等于y x is y x和y是同一个 对象 x is not y x和y是不同 对象 x in y x是y容器(例如,序列) 的成员 x not in y x不是y容器(例如,序列) 的成员 """ #布尔运算符 (貌似python中没有 || && !) and or not #断言(不解释) assert
#while x = 1 while x < 4: print(x) x += 1 输出: 1 2 3 count = 0 while count < 5: print (count, " 小于 5") count = count + 1 else: print (count, " 大于或等于 5") 输出: 0 小于 5 1 小于 5 2 小于 5 3 小于 5 4 小于 5 5 大于或等于 5 #for for <variable> in <sequence>: <statements> else: <statements> ##例子: for number in range(1,101):#打印1~100 print(number) dic = {‘x‘:‘1‘,‘y‘:‘2‘,‘z‘:‘3‘} for key in dic: print(key + ":",dic.get(key)) 输出: x: 1 z: 3 y: 2 dic = {‘x‘:‘1‘,‘y‘:‘2‘,‘z‘:‘3‘} for key,val in dic.items(): print(key + ":",val) 输出: z: 3 y: 2 x: 1 #break,continue 略 #pass pass是空语句,是为了保持程序结构的完整性。 #迭代工具 ##zip (zip可以处理不等长序列,最短的序列“用完”的时候就会停止) >>> a = ["x","y","z"] >>> b = ["1","2","3"] >>> list(zip(a,b)) [(‘x‘, ‘1‘), (‘y‘, ‘2‘), (‘z‘, ‘3‘)] #加入循环 a = ["x","y","z"] b = ["1","2","3","4"] for letter,num in zip(a,b): print(letter,num) 输出: x 1 y 2 z 3 ##enumerate 对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标(好绕,明白就行) a = ["x","y","z"] for i,letter in enumerate(a): print(i,a[i]) 输出: 0 x 1 y 2 z #reversed和sorted 翻转和排序迭代 >>> sorted("Hello,woeld!") [‘!‘, ‘,‘, ‘H‘, ‘d‘, ‘e‘, ‘e‘, ‘l‘, ‘l‘, ‘l‘, ‘o‘, ‘o‘, ‘w‘] >>> list(reversed("Hello,woeld!")) [‘!‘, ‘d‘, ‘l‘, ‘e‘, ‘o‘, ‘w‘, ‘,‘, ‘o‘, ‘l‘, ‘l‘, ‘e‘, ‘H‘] ##while True 略
四.列表推导式和pass、del、exec
#列表推导式是利用其他列表创建新列表的一种方法 >>> [x*x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [x*x for x in range(10) if x % 3 == 0] [0, 9, 36, 81] >>> [x+1 for x in range(10)] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [(x,y) for x in range(3) for y in range(3)] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] 还可以 >>> girls = [‘alice‘,‘bernice‘,‘clarice‘] >>> boys = [‘charis‘,‘arnold‘,‘bob‘] >>> letterGirls = {} >>> for girl in girls: letterGirls.setdefault(girl[0],[]).append(girl)#还可以这么用,我服,查了下setdefault(key[, default])如果key在字典中,则返回其值。如果没有,则插入值为default的key,并返回default。原来返回了列表,难怪能append! >>> letterGirls {‘c‘: [‘clarice‘], ‘b‘: [‘bernice‘], ‘a‘: [‘alice‘]} >>> print([b+"+"+g for b in boys for g in letterGirls[b[0]]]) [‘charis+clarice‘, ‘arnold+alice‘, ‘bob+bernice‘]
#pass pass是空语句,是为了保持程序结构的完整性。 #del删除变量 #exec和eval回头再研究吧
参考《Python基础教程》(第2版)·修订版
标签:abc 列表 ted condition sequence 就会 元组 删除 cond
原文地址:http://www.cnblogs.com/Tabby/p/7487891.html