#列表解析(本质就是迭代) List = [1, 3, 5] L = [x*2 for x in List] print(L) #读取文件内容 for line in open("wy.txt"): print(line) #输出结果 ''' wang yang good luck''' #函数rstrip移除字符串右边的空白符 file = open("wy.txt") lines = file.readlines() result = [line.rstrip() for line in lines] for text in result: print(text) #输出结果为 ''' wang yang good luck ''' #扩展列表解析 specialLine = [line.rstrip() for line in open("wy.txt") if line[0] == 'w']#if会对每读取出的一行line进行判断。 print(specialLine) res = [x+y for x in "abc" for y in "123"] #两个字符串的排列组合 print(res) '''结果为:['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']''' #等价代码 res1 = [] for x in "abc": for y in "123": res1.append(x+y) print(res1) '''结果为:['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']''' inputStr = input("please input s string:") charRes = [ord(c) for c in inputStr] print(charRes) sum = 0 for c in inputStr: sum += ord(c) print("The sum of all characters is %d" % sum) def GetAscii(string): ''' Get the list of every character in string ''' L = [ord(c) for c in inputStr] return L print(GetAscii(inputStr)) print(map(ord, inputStr)) phonebook = {"wang":1233, "zhang":56566, "li":37756, "xu":44455} allKeys = phonebook.keys(); sorted(allKeys) for key in allKeys: print("%s %s" % (key, phonebook[key]))