1.参数带一个星表示组元,带两个星表示字典
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg inarguments:
print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys:
print(kw,":", keywords[kw])
cheeseshop("Limburger", "It's very runny,sir.",
"It'sreally very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="CheeseShop Sketch")
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
2.list
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number,square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwisean error is raised
>>> [x, x**2 for x in range(6)]
File "<stdin>",line 1, in ?
[x, x**2 for x inrange(6)]
^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two'for'
>>> 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]
3.Set
>>> basket = {'apple', 'orange', 'apple', 'pear','orange', 'banana'}
>>> print(basket) # show that duplicateshave been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on unique lettersfrom two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # uniqueletters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in abut not in b
{'r', 'd', 'b'}
>>> a | b # letters ineither a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in botha and b
{'a', 'c'}
>>> a ^ b # letters in a orb but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
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())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
5. loop
5.1 enumerate
When looping through a sequence, the position index andcorresponding 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
5.2 zip()
>>> questions = ['name', 'quest', 'favoritecolor']
>>> answers = ['lancelot', 'the holy grail','blue']
>>> for q, a in zip(questions, answers):
... print('Whatis 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.
5.3reversed()
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
5.4 [:]
To change a sequence you are iterating over while inside theloop (for example to duplicate certain items), it is recommended that you firstmake a copy. Looping over a sequence does not implicitly make a copy. The slicenotation 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']
6. condition
A and not B or C is equivalent to (A and (not B)) or C
(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)
7.output
>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # Note use of'end' on previous line
... print(repr(x*x*x).rjust(4))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>> for x in range(1, 11):
... print('{0:2d}{1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
'!a' (apply ascii()), '!s' (apply str()) and '!r' (applyrepr()) can be used to convert the value before it is formatted:
>>> import math
>>> print('The value of PI is approximately{}.'.format(math.pi))
The value of PI is approximately 3.14159265359.
>>> print('The value of PI is approximately{!r}.'.format(math.pi))
The value of PI is approximately 3.141592653589793.
An optional ':' and format specifier can follow the fieldname. This allows greater control over how the value is formatted. Thefollowing example rounds Pi to three places after the decimal.
>>> import math
>>> print('The value of PI is approximately{0:.3f}.'.format(math.pi))
The value of PI is approximately 3.142.
%
>>> import math
>>> print('The value of PI is approximately%5.3f.' % math.pi)
The value of PI is approximately 3.142.
The problem with this code is that it leaves the file openfor an indeterminate amount of time after this part of the code has finishedexecuting. This is not an issue in simple scripts, but can be a problem forlarger applications. The with statement allows objects like files to be used ina way that ensures they are always cleaned up promptly and correctly.
with open("myfile.txt") as f:
for line in f:
print(line,end="")