SlideShare a Scribd company logo
Python легко и просто. Красиво решаем повседневные задачи
Python: легко и просто.
Красиво решаем повседневные задачи.
Александр Семенюк
a_semianiuk@wargaming.net
Python делает всё, чтобы упростить вашу жизнь.
Этот язык предоставляет многообразие инструментов,
позволяющих легко решать многие задачи.
if len(mylist) == 0:
raise Exception('Empty list is not acceptable')
>>> bool( 0 )
False
>>> bool( [] )
False
>>> bool( {} )
False
>>> bool( None )
False
>>> bool( '' )
False
if mylist:
raise Exception('Empty list is not acceptable')
class Basket(object):
empty = True
items = []
def __nonzero__(self):
return not self.empty
def __len__(self):
return len(self.items)
basket = Basket()
print bool(basket) # False
if mylist == None:
do_something()
if mylist == None:
do_something()
if mylist is None:
do_something()
$ 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
• Всё в Python – это объект.
• Каждая переменная – ссылка на объект.
• Оператор is сравнивает эти ссылки.
class A:
pass
a = A()
b = a
print a is b
print id(a)
print id(b)
True
33274616
33274616
• В Python есть неизменяемые объекты. Их значение не меняется
после создания:
• Числа - 0, 245, 10000000000000001
• Строки - 'Hi people!'
• Кортежи (неизменяемые списки) - (1,2, 'a')
• И, конечно же, None !
if mylist:
raise Exception('Empty list is not acceptable')
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
…
class EmptyListError(Exception):
pass
if not mylist:
raise EmptyListError('Empty list is not acceptable')
try:
work_with_list([])
except EmptyListError:
# we know what's wrong
try:
work_with_list([])
except Exception:
# what to do?
• Python знает, где истина.
• ‘is None’ лучше, чем ‘== None’.
• Всё объект!
• Создавать свои собственные исключения круто.
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()
for i in range(len(mylist)):
print mylist[i]
for i in range(len(mylist)):
print mylist[i]
for item in mylist:
print item
import itertools
for i in itertools.count():
print i
for item in reversed(mylist):
print item
for item in reversed(mylist):
print item
>>> mylist = [1,2,3]
>>> mylist[::-1]
[3, 2, 1]
$ 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
$ 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
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]
for hero, color in zip(heroes, colors):
print hero, 'is', color
heroes_with_colors = dict(zip(heroes, colors))
print heroes_with_colors
{
'Spiderman': 'red',
'Batman': 'black',
'Hulk': 'green'
}
from itertools import izip
for hero, color in izip(heroes, colors):
print hero, 'is', color
>>> for i in 'python': i
...
'p'
'y'
't'
'h'
'o'
'n'
>>> for i in 'python': i
...
'p'
'y'
't'
'h'
'o'
'n'
>>> for key in heroes_with_colors: key
...
'Spiderman'
'Batman'
'Hulk'
>>> 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
...
>>> for line in myfile:
... print repr(line) # each line in a file
...
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()
def iterate_lines(f):
for line in f:
line = line.strip(' n')
if not line:
continue
if line.startswith('#'):
continue
yield line
f = open('config.txt')
try:
for line in iterate_lines(f):
do_some_staff(line)
finally:
f.close()
>>> mylist
['a', 'b', 'b', 'c']
>>> for index, item in enumerate(mylist):
... if item == 'b':
... del mylist[index]
...
>>> mylist
['a', 'b', 'c']
>>> mydict
{'b': 2}
>>> for key in mydict:
... if key == 'b':
... del mydict[key]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> for key in mydict.keys():
... if key == 'b':
... del mydict[key]
...
>>> mydict
{}
f = open('config.txt')
try:
for line in iterate_lines(f):
do_some_staff(line)
finally:
f.close()
with EXPR as VAR:
BLOCK
with open('config.txt') as f:
process_file(f)
try:
dangerous_actions()
except AttributeError:
pass # we don't care
from contextlib import contextmanager
@contextmanager
def ignore_errors(*errors):
try:
yield
except errors:
pass
>>> with ignore_errors(KeyError, AttributeError):
... raise KeyError
...
>>>
with open('config.txt') as f:
for line in iterate_lines(f):
do_some_staff(line)
• Итерируйтесь правильно
• Отделяйте административную логику от бизнес логики
• Не изменяйте список, по которому итерируетесь
• Контекстные менеджеры молодцы
Большое спасибо за внимание!

More Related Content

PDF
Class 5: If, while & lists
PDF
Class 2: Welcome part 2
PDF
Class 3: if/else
PDF
Stupid Awesome Python Tricks
PDF
Advanced Patterns with io.ReadWriter
PDF
Class 4: For and while
PPTX
Python Workshop
PDF
Python Basic
Class 5: If, while & lists
Class 2: Welcome part 2
Class 3: if/else
Stupid Awesome Python Tricks
Advanced Patterns with io.ReadWriter
Class 4: For and while
Python Workshop
Python Basic

What's hot (20)

PPTX
Baabtra.com little coder chapter - 4
PDF
Class 7a: Functions
PDF
프알못의 Keras 사용기
PDF
iOS와 케라스의 만남
PPTX
Build a compiler in 2hrs - NCrafts Paris 2015
PPTX
Python programming
PDF
Python fundamentals - basic | WeiYuan
PDF
Intro to Python
PDF
Programação Assíncrona com Kotlin Coroutines
PDF
Python 101 1
PPTX
Recursive implicit proofs with Shapeless HLists
PDF
From 0 to mine sweeper in pyside
PDF
Python introduction 2
PDF
Implode & Explode in PHP
PDF
Fizz and buzz of computer programs in python.
KEY
Joshua Wehner - Tomorrows Programming Languages Today
PDF
2 × 3 = 6
PPTX
Sequence Types in Python Programming
PPT
Lecture 6
PDF
Random And Dynamic Images Using Python Cgi
Baabtra.com little coder chapter - 4
Class 7a: Functions
프알못의 Keras 사용기
iOS와 케라스의 만남
Build a compiler in 2hrs - NCrafts Paris 2015
Python programming
Python fundamentals - basic | WeiYuan
Intro to Python
Programação Assíncrona com Kotlin Coroutines
Python 101 1
Recursive implicit proofs with Shapeless HLists
From 0 to mine sweeper in pyside
Python introduction 2
Implode & Explode in PHP
Fizz and buzz of computer programs in python.
Joshua Wehner - Tomorrows Programming Languages Today
2 × 3 = 6
Sequence Types in Python Programming
Lecture 6
Random And Dynamic Images Using Python Cgi
Ad

Viewers also liked (6)

PPT
Breakfast forward2013kevinmurphy
PDF
Fabric для управления серверами
PDF
Physical is the new digital
PPTX
World tourism asia&europe
PDF
Branded Entertainment in Asia
PDF
Asia Entertainment & Resorts Nov. 2009 Investor Presentation
Breakfast forward2013kevinmurphy
Fabric для управления серверами
Physical is the new digital
World tourism asia&europe
Branded Entertainment in Asia
Asia Entertainment & Resorts Nov. 2009 Investor Presentation
Ad

Similar to Python легко и просто. Красиво решаем повседневные задачи (20)

PPTX
Python Workshop - Learn Python the Hard Way
PDF
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
PDF
Beautiful python - PyLadies
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
PPTX
beginners_python_cheat_sheet_pcc_all (3).pptx
PDF
python codes
PDF
beginners_python_cheat_sheet_pcc_all.pdf
PDF
Beginner's Python Cheat Sheet.pdf
PDF
beginners_python_cheat_sheet_pcc_all.pdf
PPTX
cover every basics of python with this..
DOCX
CS3401- Algorithmto use for data structure.docx
PPTX
Arrow 101 - Kotlin funcional com Arrow
PPTX
Python Lecture 11
PDF
Learn 90% of Python in 90 Minutes
PPTX
Keep it Stupidly Simple Introduce Python
DOCX
ECE-PYTHON.docx
PDF
Python
PDF
Practical File Grade 12.pdf
PDF
beginners_python_cheat_sheet_pcc_all_bw.pdf
Python Workshop - Learn Python the Hard Way
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
Beautiful python - PyLadies
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
beginners_python_cheat_sheet_pcc_all (3).pptx
python codes
beginners_python_cheat_sheet_pcc_all.pdf
Beginner's Python Cheat Sheet.pdf
beginners_python_cheat_sheet_pcc_all.pdf
cover every basics of python with this..
CS3401- Algorithmto use for data structure.docx
Arrow 101 - Kotlin funcional com Arrow
Python Lecture 11
Learn 90% of Python in 90 Minutes
Keep it Stupidly Simple Introduce Python
ECE-PYTHON.docx
Python
Practical File Grade 12.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdf

Recently uploaded (20)

PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Cell Types and Its function , kingdom of life
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Anesthesia in Laparoscopic Surgery in India
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Cell Structure & Organelles in detailed.
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
01-Introduction-to-Information-Management.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Microbial diseases, their pathogenesis and prophylaxis
Week 4 Term 3 Study Techniques revisited.pptx
VCE English Exam - Section C Student Revision Booklet
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Complications of Minimal Access Surgery at WLH
Cell Types and Its function , kingdom of life
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Module 4: Burden of Disease Tutorial Slides S2 2025
human mycosis Human fungal infections are called human mycosis..pptx
Anesthesia in Laparoscopic Surgery in India

Python легко и просто. Красиво решаем повседневные задачи

  • 2. Python: легко и просто. Красиво решаем повседневные задачи. Александр Семенюк a_semianiuk@wargaming.net
  • 3. Python делает всё, чтобы упростить вашу жизнь. Этот язык предоставляет многообразие инструментов, позволяющих легко решать многие задачи.
  • 4. if len(mylist) == 0: raise Exception('Empty list is not acceptable')
  • 5. >>> bool( 0 ) False >>> bool( [] ) False >>> bool( {} ) False >>> bool( None ) False >>> bool( '' ) False
  • 6. if mylist: raise Exception('Empty list is not acceptable')
  • 7. class Basket(object): empty = True items = [] def __nonzero__(self): return not self.empty def __len__(self): return len(self.items) basket = Basket() print bool(basket) # False
  • 8. if mylist == None: do_something()
  • 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 !
  • 13. if mylist: raise Exception('Empty list is not acceptable')
  • 14. BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError | +-- BufferError | +-- ArithmeticError | | +-- FloatingPointError | | +-- OverflowError | | +-- ZeroDivisionError …
  • 15. class EmptyListError(Exception): pass if not mylist: raise EmptyListError('Empty list is not acceptable')
  • 16. try: work_with_list([]) except EmptyListError: # we know what's wrong try: work_with_list([]) except Exception: # what to do?
  • 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()
  • 19. for i in range(len(mylist)): print mylist[i]
  • 20. for i in range(len(mylist)): print mylist[i] for item in mylist: print item
  • 21. import itertools for i in itertools.count(): print i
  • 22. for item in reversed(mylist): print item
  • 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
  • 28. heroes_with_colors = dict(zip(heroes, colors)) print heroes_with_colors { 'Spiderman': 'red', 'Batman': 'black', 'Hulk': 'green' }
  • 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
  • 36. f = open('config.txt') try: for line in iterate_lines(f): do_some_staff(line) finally: f.close()
  • 37. >>> mylist ['a', 'b', 'b', 'c'] >>> for index, item in enumerate(mylist): ... if item == 'b': ... del mylist[index] ... >>> mylist ['a', 'b', 'c']
  • 38. >>> mydict {'b': 2} >>> for key in mydict: ... if key == 'b': ... del mydict[key] ... Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration
  • 39. >>> for key in mydict.keys(): ... if key == 'b': ... del mydict[key] ... >>> mydict {}
  • 40. f = open('config.txt') try: for line in iterate_lines(f): do_some_staff(line) finally: f.close()
  • 41. with EXPR as VAR: BLOCK
  • 42. with open('config.txt') as f: process_file(f)
  • 44. from contextlib import contextmanager @contextmanager def ignore_errors(*errors): try: yield except errors: pass
  • 45. >>> with ignore_errors(KeyError, AttributeError): ... raise KeyError ... >>>
  • 46. with open('config.txt') as f: for line in iterate_lines(f): do_some_staff(line)
  • 47. • Итерируйтесь правильно • Отделяйте административную логику от бизнес логики • Не изменяйте список, по которому итерируетесь • Контекстные менеджеры молодцы