Python3 tutorial day2
list
count(item)返回item的出现次数
insert(index,x)在位置index插入x
append(item)在尾部添加item
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
[66.25, 333, -1, 333, 1, 1234.5]
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
extend(L)
remove(x)
pop(index)
sort()
reverse()
>>> a.pop()
1234.5
>>> a.remove(-1)
>>> a
[66.25, 333, 333, 1]
>>> a.sort()
>>> a
[1, 66.25, 333, 333]
>>> a.reverse()
>>> a
[333, 333, 66.25, 1]
popleft()
from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Graham")
>>> queue.popleft()
'Eric'
>>> queue
deque(['John', 'Michael', 'Graham'])
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = list(map(lambda x: x**2, range(10)))
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> b = [x**2 for x in range(10)]
>>> b
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> tx = [weapon.strip() for weapon in freshfruit]
>>> tx
['banana', 'loganberry', 'passion fruit']
>>>
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
矩阵转置
>>> matrix=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
>>> [row[i] for row in matrix]
[4, 8, 12]
>>> i
3
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
>>> [row[i] for row in matrix for i in range(4)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>>
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
>>>
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
tuples and sequences
tuples immutable
>>> v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
>>> v[1] = [222]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> v[1]
[3, 2, 1]
>>> v[1][0] = 0
>>> v
([1, 2, 3], [0, 2, 1])
>>>
Sets
A set is an unordered collection with no duplicate elements.
new empty
>>> aset = set()
>>> aset
set()
>>> aset.add(1)
>>> aset
{1}
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
{'orange', 'pear', 'banana', 'apple'}
>>> 'orange' in basket
True
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a-b
{'r', 'b', 'd'}
>>> a | b
{'a', 'c', 'b', 'd', 'm', 'l', 'r', 'z'}
>>> a & b
{'a', 'c'}
>>> a ^ b
{'b', 'd', 'm', 'l', 'r', 'z'}
a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
Dictionaries
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>> tel['jack']
4098
>>> dic1 = {}
>>> dic1
{}
>>> dic1['a'] = 1
>>> dic1
{'a': 1}
>>> dic2 = dic()
>>> dic2
{}
>>> dic2[2] = 1
>>> dic2
{2: 1}
LOOP
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
>>> 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.
To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
>>> words = ['cat', 'window', 'defenestrate']
>>> 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']
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
>>> string1
''
>>> string2
'Trondheim'
>>> string3
'Hammer Dance'
>>> non_null = string1 or string3 or string2
>>> non_null
'Hammer Dance'