Мы создали этот шпаргалка Python 3 изначально для студентов Полный разработчик Python в 2020 году: от нуля до мастерства Но теперь мы делимся этим с любыми начинающими Python, чтобы помочь им учиться и запомнить синтаксис общего питона, а также с промежуточными и продвинутыми разработчиками Python в качестве удобной ссылки. Если вы хотите загрузить PDF -версию этого шпаргалки Python, вы можете получить его Здесь !
Advanced Python:Модули,Итераторы,Генераторы,Декораторы,Класс,Исключения,Аргументы командной строки,Файл io,Полезные библиотеки
Числа
2 основных типа Python для чисел – int и float (или численность чисел и числа плавающей запятой)
type(1) # int
type(-10) # int
type(0) # int
type(0.0) # float
type(2.2) # float
type(4E2) # float - 4*10 to the power of 2
# Arithmetic
10 + 3 # 13
10 - 3 # 7
10 * 3 # 30
10 ** 3 # 1000
10 / 3 # 3.3333333333333335
10 // 3 # 3 --> floor division - no decimals and returns an int
10 % 3 # 1 --> modulo operator - return the reminder. Good for deciding if number is even or odd
# Basic Functions
pow(5, 2) # 25 --> like doing 5**2
abs(-50) # 50
round(5.46) # 5
round(5.468, 2)# 5.47 --> round to nth digit
bin(512) # '0b1000000000' --> binary format
hex(512) # '0x200' --> hexadecimal format
# Converting Strings to Numbers
age = input("How old are you?")
age = int(age)
pi = input("What is the value of pi?")
pi = float(pi)
Строки
Строки в Python как хранятся как последовательности букв в памяти
type('Hellloooooo') # str
'I\'m thirsty'
"I'm thirsty"
"\n" # new line
"\t" # adds a tab
'Hey you!'[4] # y
name = 'Andrei Neagoie'
name[4] # e
name[:] # Andrei Neagoie
name[1:] # ndrei Neagoie
name[:1] # A
name[-1] # e
name[::1] # Andrei Neagoie
name[::-1] # eiogaeN ierdnA
name[0:10:2]# Ade e
# : is called slicing and has the format [ start : end : step ]
'Hi there ' + 'Timmy' # 'Hi there Timmy' --> This is called string concatenation
'*'*10 # **********
# Basic Functions
len('turtle') # 6
# Basic Methods
' I am alone '.strip() # 'I am alone' --> Strips all whitespace characters from both ends.
'On an island'.strip('d') # 'On an islan' --> # Strips all passed characters from both ends.
'but life is good!'.split() # ['but', 'life', 'is', 'good!']
'Help me'.replace('me', 'you') # 'Help you' --> Replaces first with second param
'Need to make fire'.startswith('Need')# True
'and cook rice'.endswith('rice') # True
'bye bye'.index('e') # 2
'still there?'.upper() # STILL THERE?
'HELLO?!'.lower() # hello?!
'ok, I am done.'.capitalize() # 'Ok, I am done.'
'oh hi there'.find('i') # 4 --> returns the starting index position of the first occurrence
'oh hi there'.count('e') # 2
# String Formatting
name1 = 'Andrei'
name2 = 'Sunny'
print(f'Hello there {name1} and {name2}') # Hello there Andrei and Sunny - Newer way to do things as of python 3.6
print('Hello there {}, {}'.format(name1, name2))# Hello there Andrei and Sunny
print('Hello there %s and %s' %(name1, name2)) # Hello there Andrei and Sunny --> you can also use %d, %f, %r for integers, floats, string representations of objects respectively
# Palindrome check
word = 'reviver'
p = bool(word.find(word[::-1]) + 1)
print(p) # True
Логический
Правда или ложь. Используется во многих сравнениях и логических операциях в Python
bool(True)
bool(False)
# all of the below evaluate to False. Everything else will evaluate to True in Python.
print(bool(None))
print(bool(False))
print(bool(0))
print(bool(0.0))
print(bool([]))
print(bool({}))
print(bool(()))
print(bool(''))
print(bool(range(0)))
print(bool(set()))
# See Logical Operators and Comparison Operators section for more on booleans.
Списки
В отличие от струн, списки являются изменчивыми последовательностями в Python
my_list = [1, 2, '3', True]# We assume this list won't mutate for each example below
len(my_list) # 4
my_list.index('3') # 2
my_list.count(2) # 1 --> count how many times 2 appears
my_list[3] # True
my_list[1:] # [2, '3', True]
my_list[:1] # [1]
my_list[-1] # True
my_list[::1] # [1, 2, '3', True]
my_list[::-1] # [True, '3', 2, 1]
my_list[0:3:2] # [1, '3']
# : is called slicing and has the format [ start : end : step ]
# Add to List
my_list * 2 # [1, 2, '3', True, 1, 2, '3', True]
my_list + [100] # [1, 2, '3', True, 100] --> doesn't mutate original list, creates new one
my_list.append(100) # None --> Mutates original list to [1, 2, '3', True, 100] # Or: += []
my_list.extend([100, 200]) # None --> Mutates original list to [1, 2, '3', True, 100, 200]
my_list.insert(2, '!!!') # None --> [1, 2, '!!!', '3', True] - Inserts item at index and moves the rest to the right.
' '.join(['Hello','There'])# 'Hello There' --> Joins elements using string as separator.
# Copy a List
basket = ['apples', 'pears', 'oranges']
new_basket = basket.copy()
new_basket2 = basket[:]
# Remove from List
[1,2,3].pop() # 3 --> mutates original list, default index in the pop method is -1 (the last item)
[1,2,3].pop(1) # 2 --> mutates original list
[1,2,3].remove(2)# None --> [1,3] Removes first occurrence of item or raises ValueError.
[1,2,3].clear() # None --> mutates original list and removes all items: []
del [1,2,3][0] #
# Ordering
[1,2,5,3].sort() # None --> Mutates list to [1, 2, 3, 5]
[1,2,5,3].sort(reverse=True) # None --> Mutates list to [5, 3, 2, 1]
[1,2,5,3].reverse() # None --> Mutates list to [3, 5, 2, 1]
sorted([1,2,5,3]) # [1, 2, 3, 5] --> new list created
list(reversed([1,2,5,3]))# [3, 5, 2, 1] --> reversed() returns an iterator
# Get First and Last element of a list
mList = [63, 21, 30, 14, 35, 26, 77, 18, 49, 10]
first, *x, last = mList
print(first) #63
print(last) #10
# Matrix
matrix = [[1,2,3], [4,5,6], [7,8,9]]
matrix[2][0] # 7 --> Grab first first of the third item in the matrix object
# Looping through a matrix by rows:
mx = [[1,2,3],[4,5,6]]
for row in range(len(mx)):
for col in range(len(mx[0])):
print(mx[row][col]) # 1 2 3 4 5 6
# Transform into a list:
[mx[row][col] for row in range(len(mx)) for col in range(len(mx[0]))] # [1,2,3,4,5,6]
# Combine columns with zip and *:
[x for x in zip(*mx)] # [(1, 3), (2, 4)]
# List Comprehensions
# new_list[ for in if ]
a = [i for i in 'hello'] # ['h', 'e', 'l', 'l', '0']
b = [i*2 for i in [1,2,3]] # [2, 4, 6]
c = [i for i in range(0,10) if i % 2 == 0]# [0, 2, 4, 6, 8]
# Read line of a file into a list
with open("myfile.txt") as f:
lines = [line.strip() for line in f]
Словари
Также известен как отображения или хэш -таблицы. Это пары ключевых значений, которые гарантированно сохранят порядок вставки, начиная с Python 3.7
my_dict = {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False}
my_dict['name'] # Andrei Neagoie
len(my_dict) # 3
list(my_dict.keys()) # ['name', 'age', 'magic_power']
list(my_dict.values()) # ['Andrei Neagoie', 30, False]
list(my_dict.items()) # [('name', 'Andrei Neagoie'), ('age', 30), ('magic_power', False)]
my_dict['favourite_snack'] = 'Grapes'# {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes'}
my_dict.get('age') # 30 --> Returns None if key does not exist.
my_dict.get('ages', 0 ) # 0 --> Returns default (2nd param) if key is not found
#Remove key
del my_dict['name']
my_dict.pop('name', None)
my_dict.update({'cool': True}) # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}
{**my_dict, **{'cool': True} } # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}
new_dict = dict([['name','Andrei'],['age',32],['magic_power',False]]) # Creates a dict from collection of key-value pairs.
new_dict = dict(zip(['name','age','magic_power'],['Andrei',32, False]))# Creates a dict from two collections.
new_dict = my_dict.pop('favourite_snack') # Removes item from dictionary.
# Dictionary Comprehension
{key: value for key, value in new_dict.items() if key == 'age' or key == 'name'} # {'name': 'Andrei', 'age': 32} --> Filter dict by keys
Кортежи
Как списки, но они используются для неизменной вещи (которые не меняются)
new_list = [1,2,3,3,3,4,4,5,6,1]
set(new_list) # {1, 2, 3, 4, 5, 6}
my_set.remove(100) # {1} --> Raises KeyError if element not found
my_set.discard(100) # {1} --> Doesn't raise an error if element not found
my_set.clear() # {}
new_set = {1,2,3}.copy()# {1,2,3}
# Frozenset
# hashable --> it can be used as a key in a dictionary or as an element in a set.
= frozenset()
Никто
Никто не используется для отсутствия значения и может быть использован, чтобы показать, что ничего не было назначено объекту
type(None) # NoneType
a = None
Операторы сравнения
== # equal values
!= # not equal
> # left operand is greater than right operand
< # left operand is less than right operand
>= # left operand is greater than or equal to right operand
<= # left operand is less than or equal to right operand
is # check if two operands refer to same object in memory
Логические операторы
1 < 2 and 4 > 1 # True
1 > 3 or 4 > 1 # True
1 is not 4 # True
not True # False
1 not in [2,3,4]# True
if :
# perform action1
elif :
# perform action2
else:
# perform action3
Петли
my_list = [1,2,3]
my_tuple = (1,2,3)
my_list2 = [(1,2), (3,4), (5,6)]
my_dict = {'a': 1, 'b': 2. 'c': 3}
for num in my_list:
print(num) # 1, 2, 3
for num in my_tuple:
print(num) # 1, 2, 3
for num in my_list2:
print(num) # (1,2), (3,4), (5,6)
for num in '123':
print(num) # 1, 2, 3
for k,v in my_dict.items(): # Dictionary Unpacking
print(k) # 'a', 'b', 'c'
print(v) # 1, 2, 3
while :
# action
if :
break # break out of while loop
if :
continue # continue to the next line in the block
# waiting until user quits
msg = ''
while msg != 'quit':
msg = input("What should I do?")
print(msg)
from collections import namedtuple
Person = namedtuple('Person', 'name height')
person = Person('Jean-Luc', 187)
f'{person.height}' # '187'
'{p.height}'.format(p=person)# '187'
Заказан
Поддерживает порядок введения
from collections import OrderedDict
# Store each person's languages, keeping # track of who responded first.
programmers = OrderedDict()
programmers['Tim'] = ['python', 'javascript']
programmers['Sarah'] = ['C++']
programmers['Bia'] = ['Ruby', 'Python', 'Go']
for name, langs in programmers.items():
print(name + '-->')
for lang in langs:
print('\t' + lang)
Функции
*args и ** kwargs
SPLAT (*) расширяет коллекцию в позиционные аргументы, в то время как Splatty-Splat (**) расширяет словарь в аргументы ключевых слов.
SPLAT объединяет ноль или более позиционных аргументов в кортеж, в то время как Splatty-Splat объединяет ноль или более аргументов ключевых слов в словаре.
# Factorial
from functools import reduce
n = 3
factorial = reduce(lambda x, y: x*y, range(1, n+1))
print(factorial) #6
# Fibonacci
fib = lambda n : n if n <= 1 else fib(n-1) + fib(n-2)
result = fib(10)
print(result) #55
Понимание
= [i+1 for i in range(10)] # [1, 2, ..., 10]
= {i for i in range(10) if i > 5} # {6, 7, 8, 9}
= (i+5 for i in range(10)) # (5, 6, ..., 14)
= {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
output = [i+j for i in range(3) for j in range(3)] # [0, 1, 2, 1, 2, 3, 2, 3, 4]
# Is the same as:
output = []
for i in range(3):
for j in range(3):
output.append(i+j)
Тройное состояние
# if else
[a if a else 'zero' for a in [0, 1, 0, 3]] # ['zero', 1, 'zero', 3]
any([False, True, False])# True if at least one item in collection is truthy, False if empty.
all([True,1,3,True]) # True if all items in collection are true
Закрытие
У нас есть закрытие в Python, когда:
Вложенная функция ссылается на значение своей функции вложения, а затем
Функция вложения возвращает вложенную функцию.
def get_multiplier(a):
def out(b):
return a * b
return out
Если многочисленные вложенные функции в рамках функции ссылаются на одно и то же значение, это значение поделится.
Для первого свободного использования функции динамического доступа' .__ Закрытие __ [0] .cell_contents'.
Сфера
Если переменная присваивается в любом месте прицела, она рассматривается как локальная переменная, если только она не объявлена «глобальной» или «нелокальной».
def get_counter():
i = 0
def out():
nonlocal i
i += 1
return i
return out
Декоратор Это печатает имя функции каждый раз, когда ее вызывают.
from functools import wraps
def debug(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
return func(*args, **kwargs)
return out
@debug
def add(x, y):
return x + y
Обертки – это помощник -помощник, который копирует метаданные функции add () для функционирования ().
Без этого'добавить .__ name__'вернется'вне'.
Учебный класс
Пользовательские объекты создаются с помощью ключевого слова класса
class :
age = 80 # Class Object Attribute
def __init__(self, a):
self.a = a # Object Attribute
@classmethod
def get_class_name(cls):
return cls.__name__
Наследование
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age, staff_num):
super().__init__(name, age)
self.staff_num = staff_num
Множественное наследство
class A: pass
class B: pass
class C(A, B): pass
MRO определяет порядок, в котором родительские классы проходят при поиске метода:
>>> C.mro()
[, , , ]
Исключения
try:
5/0
except ZeroDivisionError:
print("No division by zero!")
while True:
try:
x = int(input('Enter your age: '))
except ValueError:
print('Oops! That was no valid number. Try again...')
else: # code that depends on the try block running successfully should be placed in the else block.
print('Carry on!')
break
Открывает файл и возвращает соответствующий объект файла.
= open('', mode='r', encoding=None)
Режимы
'r'– Читать (по умолчанию).
'w'– написать (усечение).
'x'– Напишите или сбой, если файл уже существует.
'a'– добавить.
'w+'– Читать и написать (усечение).
'r+'– Читайте и пишите с самого начала.
'a+'– Читайте и пишите с конца.
't'– текстовый режим (по умолчанию).
'b'– двоичный режим.
Файл
.seek(0) # Moves to the start of the file.
= .readline() # Returns a line.
= .readlines() # Returns a list of lines.
.write() # Writes a string or bytes object.
.writelines() # Writes a list of strings or bytes objects.
Методы не добавляют и не разделяют новеньши.
Читать текст из файла
def read_file(filename):
with open(filename, encoding='utf-8') as file:
return file.readlines() # or read()
for line in read_file(filename):
print(line)
Написать текст в файл
def write_to_file(filename, text):
with open(filename, 'w', encoding='utf-8') as file:
file.write(text)
Добавить текст подать
def append_to_file(filename, text):
with open(filename, 'a', encoding='utf-8') as file:
file.write(text)
CSV
import csv
Читать строки из файла CSV
def read_csv_file(filename):
with open(filename, encoding='utf-8') as file:
return csv.reader(file, delimiter=';')
Записать строки в файл csv
def write_to_csv_file(filename, rows):
with open(filename, 'w', encoding='utf-8') as file:
writer = csv.writer(file, delimiter=';')
writer.writerows(rows)
Json
import json
= json.dumps(
Читать объект из файла json
def read_json_file(filename):
with open(filename, encoding='utf-8') as file:
return json.load(file)
Записать объект в файл json
def write_to_json_file(filename, an_object):
with open(filename, 'w', encoding='utf-8') as file:
json.dump(an_object, file, ensure_ascii=False, indent=2)
Соленый огурец
import pickle
= pickle.dumps()
= pickle.loads()
Читать объект из файла
def read_pickle_file(filename):
with open(filename, 'rb') as file:
return pickle.load(file)
Записать объект для подачи
def write_to_pickle_file(filename, an_object):
with open(filename, 'wb') as file:
pickle.dump(an_object, file)
Профиль
Базовый
from time import time
start_time = time() # Seconds since
...
duration = time() - start_time
Математика
from math import e, pi
from math import cos, acos, sin, asin, tan, atan, degrees, radians
from math import log, log10, log2
from math import inf, nan, isinf, isnan
Статистика
from statistics import mean, median, variance, pvariance, pstdev
Случайный
from random import random, randint, choice, shuffle
random() # random float between 0 and 1
randint(0, 100) # random integer between 0 and 100
random_el = choice([1,2,3,4]) # select a random element from list
shuffle([1,2,3,4]) # shuffles a list
Использовать' .weekday ()'Чтобы получить день недели (понедельник).
'fold = 1'означает второй проход в случае отрыва времени на один час.
В настоящее время
= D/DT.today() # Current local date or naive datetime.
= DT.utcnow() # Naive datetime from current UTC time.
= DT.now() # Aware datetime from current tz time.
Часовой пояс
= UTC # UTC timezone.
= tzlocal() # Local timezone.
= gettz('/') # Timezone from 'Continent/City_Name' str.
=
.astimezone() # Datetime, converted to passed timezone.
= .replace(tzinfo=) # Unconverted object with new timezone.
Регулярно
import re
= re.sub(, new, text, count=0) # Substitutes all occurrences.
= re.findall(, text) # Returns all occurrences.
= re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches.
= re.search(, text) # Searches for first occurrence of pattern.
= re.match(, text) # Searches only at the beginning of the text.
Совместный объект
= .group() # Whole match.
= .group(1) # Part in first bracket.
= .groups() # All bracketed parts.
= .start() # Start index of a match.
= .end() # Exclusive end index of a match.
Специальные последовательности
Выражения ниже держат верно для строк, которые содержат только символы ASCII. Используйте заглавные буквы для отрицания.