Python语言强大而灵活,对于许多用其它语言(如C/C++,Java等)貌似很复杂的操作,Python往往出其不意,看后不由惊叹其简洁精妙!(不断补充中,也欢迎大家补充完善^_^)
对矩阵进行行列变换,Python代码只需一行!看如下两种方法,第一种使用嵌套的列表推导式(List Comprehensions),第二种使用zip对matrix进行展开(unpacking)。
>>> matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] >>> matrix [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] >>> transed = [[row[i] for row in matrix] for i in range(4)] >>> transed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] >>>
>>> matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] >>> matrix [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] >>> transed = zip(*matrix) >>> transed [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
注意:第二种方式,其中的元素从列表变为了元组。
通过定义一个元组(Tuple)或列表(List),甚至是字典(Dictionary),可以通过展开变量,给函数传递多个参数,如下所示:
>>> def f(x, y, z): print("x=%s"%(str(x))) print("y=%s"%(str(y))) print("z=%s"%(str(z))) >>> args = (10, "test", [100, 200]) >>> f(*args) x=10 y=test z=[100, 200] >>>
有时需要从列表 ["num0", "num1", "num2"] 构造类似 {0: "num0", 1: "num1", 2: "num2" } 形式的字典,可利用enumerate内嵌函数完成,如下所示:
>>> d = {k : v for k, v in enumerate(["num1", "num2", "num3"])} >>> d {0: 'num1', 1: 'num2', 2: 'num3'} >>>
如果需要同时遍历操作多个序列类型(str,list,tuple,unicode,bytes,buffer,xrange等),可以利用zip内嵌函数,如下所示:
>>> name = ["Guido", "Eric", "Thomas"] >>> age = [45, 34, 31] >>> city = ["New York", "Seattle", "Beijing"] >>> for n, a, c in zip(name, age, city): print("%s is %d old, working at %s."%(n, a, c)) Guido is 45 old, working at New York. Eric is 34 old, working at Seattle. Thomas is 31 old, working at Beijing. >>>
对于像str,list,tuple等序列类型,可以利用切片反转序列值,如下所示:
>>> S = "abcdefg" >>> S 'abcdefg' >>> S[::-1] 'gfedcba' >>> L = ["a", "b", "c", "d"] >>> L ['a', 'b', 'c', 'd'] >>> L[::-1] ['d', 'c', 'b', 'a'] >>> T = (1, 2, 3, 4,5) >>> T (1, 2, 3, 4, 5) >>> T[::-1] (5, 4, 3, 2, 1) >>>
对于像"[4, [5, 6]]","{'name': 'thomas', 'age': 32}"这样字符串形式的列表、字典形式,可以通过eval转换成Python的list和dict类型。这种场景主要用在用户输入或者从文件中读取。如下所示:
>>> strList = "[4, [5, 6]]" >>> strDict = "{'name': 'thomas', 'age': 32}" >>> eval(strList) [4, [5, 6]] >>> eval(strDict) {'age': 32, 'name': 'thomas'} >>>当然,eval 很强大,对于处理字符串和 Python 内部数据类型之间的转换,eval 和 str 配合使用就能达到效果。