An Informal Introduction to Python
1. Number
>>> -7//3
-3
>>> 7//-3
-3
_ 表示最后的计算结果
2. str
str是immutable的
word = "helloA"
word[1] # "e"
word[-1] #"A"
word[1:3] #"el"
word[3:1] #""
word[1:] #"elloA"
word[100] #exception
word[-100] #exception
len(word) #6
3. Unicode
"我的博客".encode("utf-8")
4. List
List和Str几乎一样,除了List是可以改变的。特别注意有些List的函数返回是None。
L=[1,2,3,4]
L=L.append(5) #none
More Control Flow Tools
1. range()
range(5) #0, 1, 2, 3, 4
range(5, 10) #5, 6, 7, 8, 9
range(0, 10, 3) #0, 3, 6, 9
range(-10, -100, -30) #-10, -40, -70
2. 定义函数
def fib(n):
rst = []
a, b = 0 ,1
while b < n:
rst.append(b)
a, b = b, a+b
return rst
print(fib(1000))
如果一个函数没有return语句,那么这个函数返回None。
3. 默认参数
def f(a, L=[]):
L.append(a)
return L
def g(a, L=None):
if(L == None):
L = []
L.append(a)
return L
print(f(1)) #[1]
print(f(2)) #[1,2]
print(f(3)) #[1,2,3]
print(g(1)) #[1]
print(g(2)) #[2]
print(g(3)) #[3]
4. Lambda
def getFun(n):
return lambda x: x+n
f=getFun(10)
print(f(21)) #31
Data Structures
1. List
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
List comprehension
>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]
Del
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
2. Tuple
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
3. Set
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
{'orange', 'bananna', 'pear', 'apple'}
>>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
{'orange', 'pear', 'apple', 'banana'}
>>> fruit = {'orange', 'apple'} # {} syntax is equivalent to [] for lists
>>> fruit
{'orange', 'apple'}
>>> 'orange' in fruit # fast membership testing
True
>>> 'crabgrass' in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in either a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Set Comprehension
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
4. Dictionary
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
Dictionary Comprehension
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
5. Looping Techniques
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
6. More on Conditions
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
7. Comparing Sequences and Other Types
(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)