9. if mylist == None:
do_something()
if mylist is None:
do_something()
10. $ python -m timeit -s "x = None" "x is None"
10000000 loops, best of 3: 0.0329 usec per loop
$ python -m timeit -s "x = None" "x == None"
10000000 loops, best of 3: 0.0607 usec per loop
11. • Всё в Python – это объект.
• Каждая переменная – ссылка на объект.
• Оператор is сравнивает эти ссылки.
class A:
pass
a = A()
b = a
print a is b
print id(a)
print id(b)
True
33274616
33274616
12. • В Python есть неизменяемые объекты. Их значение не меняется
после создания:
• Числа - 0, 245, 10000000000000001
• Строки - 'Hi people!'
• Кортежи (неизменяемые списки) - (1,2, 'a')
• И, конечно же, None !
17. • Python знает, где истина.
• ‘is None’ лучше, чем ‘== None’.
• Всё объект!
• Создавать свои собственные исключения круто.
18. try:
f = open('config.txt')
line = f.readline()
while line:
line = line.strip(' n')
if not line:
continue
if line.startswith('#'):
continue
do_some_staff(line)
line = f.readline()
finally:
f.close()
23. for item in reversed(mylist):
print item
>>> mylist = [1,2,3]
>>> mylist[::-1]
[3, 2, 1]
24. $ python -m timeit -s "l = [1, 2, 3]" "list(reversed(l))"
1000000 loops, best of 3: 0.995 usec per loop
$ python -m timeit -s "l = [1, 2, 3]" "l[::-1]"
1000000 loops, best of 3: 0.202 usec per loop
25. $ python -m timeit -s "l = [1, 2, 3]" "for i in reversed(l): pass"
1000000 loops, best of 3: 0.28 usec per loop
$ python -m timeit -s "l = [1, 2, 3]" "for i in l[::-1]: pass"
1000000 loops, best of 3: 0.318 usec per loop
26. heroes = ['Batman', 'Spiderman', 'Hulk', 'Invisible Woman']
colors = ['black', 'red', 'green']
for i in range(min(len(heroes), len(colors)):
print list1[i], 'is', list2[i]
27. for hero, color in zip(heroes, colors):
print hero, 'is', color
29. from itertools import izip
for hero, color in izip(heroes, colors):
print hero, 'is', color
30. >>> for i in 'python': i
...
'p'
'y'
't'
'h'
'o'
'n'
31. >>> for i in 'python': i
...
'p'
'y'
't'
'h'
'o'
'n'
>>> for key in heroes_with_colors: key
...
'Spiderman'
'Batman'
'Hulk'
32. >>> for i in 'python': i
...
'p'
'y'
't'
'h'
'o'
'n'
>>> for key in heroes_with_colors: key
...
'Spiderman'
'Batman'
'Hulk'
>>> import re
>>> for match in re.finditer(pattern, string):
... # each match in the string
...
33. >>> for line in myfile:
... print repr(line) # each line in a file
...
34. f = open('config.txt')
try:
for line in f:
line = line.strip(' n')
if not line:
continue
if line.startswith('#'):
continue
do_some_staff(line)
finally:
f.close()
35. def iterate_lines(f):
for line in f:
line = line.strip(' n')
if not line:
continue
if line.startswith('#'):
continue
yield line