Python 学习笔记

来源:互联网 发布:图像处理 马尔可夫算法 编辑:程序博客网 时间:2024/05/16 07:53

在http://docs.python.org/ 中学习Python ,下面写一些自己的笔记

【1】发现一个奇怪的事情,自己写的代码总是报错,而复制上面的代码却正常!

         解决:原来是不能将空格和Tab混用,在Python中,严格要求缩进,一个缩进就是一个块

【2】Python中使用j J作为复数的虚部符号。如

>>> a=1.5+0.5j>>> a.real1.5>>> a.imag0.5【3】字符串String记得加‘’
>>> 'spam eggs''spam eggs'>>> 'doesn\'t'"doesn't">>> "doesn't""doesn't">>> '"Yes," he said.''"Yes," he said.'>>> "\"Yes,\" he said."'"Yes," he said.'>>> '"Isn\'t," she said.''"Isn\'t," she said.'
>>> word[:2]    # The first two characters'He'>>> word[2:]    # Everything except the first two characters'lpA'【4】不能直接修改数组中的元素,但是可以将原数组部分与修改的值相加起来
>>> word[0] = 'x'Traceback (most recent call last):  File "<stdin>", line 1, in ?TypeError: object does not support item assignment>>> 'x' + word[1:]'xelpA'>>> 'Splat' + word[4]'SplatA'
【5】不同C/C++中的if语句,这里的if后要加冒号
>>> x = int(raw_input("Please enter an integer: "))Please enter an integer: 42>>> if x < 0:...      x = 0...      print 'Negative changed to zero'... elif x == 0:...      print 'Zero'... elif x == 1:...      print 'Single'... else:...      print 'More'...More

【6】for循环
>>> # Measure some strings:... words = ['cat', 'window', 'defenestrate']>>> for w in words:...     print w, len(w)...cat 3window 6defenestrate 12>>> for w in words[:]:  # Loop over a slice copy of the entire list....     if len(w) > 6:...         words.insert(0, w)...>>> words['defenestrate', 'cat', 'window', 'defenestrate']#若修改了数组元素的话,数组名后要加[:]

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']>>> for i in range(len(a)):...     print i, a[i]...0 Mary1 had2 a3 little4 lamb
使用range循环
这个例子比较奇怪:
>>> for n in range(2, 10):...     for x in range(2, n):...         if n % x == 0:...             print n, 'equals', x, '*', n/x...             break...     else:...         # loop fell through without finding a factor...         print n, 'is a prime number'...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3
else 语句属于for,并不是if,当没有执行break,才执行else

【7】pass可以作为注释,当你没相到的时候,可以用pass在哪里注释

【8】过滤器:
>>> def f(x): return x % 2 != 0 and x % 3 != 0...>>> filter(f, range(2, 25))[5, 7, 11, 13, 17, 19, 23]
【9】
>>> [[row[i] for row in matrix] for i in range(4)][[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]#等价于下面:>>> transposed = []>>> for i in range(4):...     transposed.append([row[i] for row in matrix])...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]#也可用zip()转置>>> zip(*matrix)[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]


	
				
		
原创粉丝点击