форкнуто от main/python-labs
Сравнить коммиты
7 Коммитов
5a15312680
...
011a3283de
Автор | SHA1 | Дата |
---|---|---|
|
011a3283de | 2 недель назад |
|
798e6b8fa3 | 2 недель назад |
|
2d43ba04f9 | 2 недель назад |
![]() |
b152453e01 | 2 недель назад |
|
205d9749b5 | 2 недель назад |
|
53a72b70a6 | 2 недель назад |
![]() |
34f088c67a | 2 недель назад |
@ -1,746 +0,0 @@
|
||||
# Отчет по теме 2
|
||||
|
||||
**Антонов Дмитрий, А-03-23**
|
||||
|
||||
### 1.Начало работы, настройка текущего каталога
|
||||
```py
|
||||
import os
|
||||
os.getcwd()
|
||||
'/Users/dmitrijantonov/Documents'
|
||||
os.chdir('//Users//dmitrijantonov//Desktop//POAC//python-labs//TEMA2//')
|
||||
os.getcwd()
|
||||
'/Users/dmitrijantonov/Desktop/POAC/python-labs/TEMA2'
|
||||
```
|
||||
|
||||
### 2.Изучение простых объектов
|
||||
```py
|
||||
f1=16;f2=3
|
||||
f1,f2
|
||||
(16, 3)
|
||||
f1;f2
|
||||
16
|
||||
3
|
||||
dir()
|
||||
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2', 'os']
|
||||
```
|
||||
- Проверил доступные методы
|
||||
```py
|
||||
dir(f1)
|
||||
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'is_integer', 'numerator', 'real', 'to_bytes']
|
||||
type(f2)
|
||||
<class 'int'>
|
||||
```
|
||||
- Удаляю созданные переменные
|
||||
```py
|
||||
del f1,f2
|
||||
dir()
|
||||
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os']
|
||||
dir(f1)
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#17>", line 1, in <module>
|
||||
dir(f1)
|
||||
NameError: name 'f1' is not defined
|
||||
```
|
||||
### 3.Изучение правил именованя переменных
|
||||
|
||||
- Правильные названия
|
||||
```py
|
||||
gg = 1.6
|
||||
hh1 = 'строка'
|
||||
```
|
||||
- Неправильные названия
|
||||
```py
|
||||
73sr=3
|
||||
SyntaxError: invalid decimal literal
|
||||
and=7
|
||||
SyntaxError: invalid syntax
|
||||
```
|
||||
|
||||
### 4.Вывод списка ключевых слов
|
||||
```py
|
||||
import keyword
|
||||
keyword.kwlist
|
||||
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
|
||||
key_words = keyword.kwlist
|
||||
```
|
||||
|
||||
### 5.Освоение встроенных функций
|
||||
|
||||
- Посмотрел список встроенных идентификаторов
|
||||
```py
|
||||
import builtins
|
||||
dir(builtins)
|
||||
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'PythonFinalizationError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '_IncompleteInputError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
|
||||
```
|
||||
- Функции модуля числа и длины
|
||||
```py
|
||||
abs(-3)
|
||||
3
|
||||
len("Hello!")
|
||||
6
|
||||
e={'b' : 2, 'a' : 1, 'c' : 3}
|
||||
len(e)
|
||||
3
|
||||
```
|
||||
- Функции min и max
|
||||
```py
|
||||
max(1,2,3,4,)
|
||||
4
|
||||
max("b","c")
|
||||
'c'
|
||||
min(-10,-50,15)
|
||||
-50
|
||||
min("b","c")
|
||||
'b'
|
||||
```
|
||||
- Математические функции
|
||||
```py
|
||||
pow(2,2)
|
||||
4
|
||||
pow(2,-2)
|
||||
0.25
|
||||
round(2.55)
|
||||
3
|
||||
round(2.50)
|
||||
2
|
||||
round(2.51)
|
||||
3
|
||||
round(2.49)
|
||||
2
|
||||
```
|
||||
- Функция сортировки и суммы
|
||||
```py
|
||||
sorted({2,3,1,1,2,-1,-4,6})
|
||||
[-4, -1, 1, 2, 3, 6]
|
||||
sorted({"s","d","a"})
|
||||
['a', 'd', 's']
|
||||
sorted({2,3,1,1,2,-1,-4,6}, reverse=True)
|
||||
[6, 3, 2, 1, -1, -4]
|
||||
sorted({"sse","dssd","aeeee"},key=len)
|
||||
['sse', 'dssd', 'aeeee']
|
||||
d ={'b': 2, 'a': 1, 'c': 3}
|
||||
d
|
||||
{'b': 2, 'a': 1, 'c': 3}
|
||||
sorted(d)
|
||||
['a', 'b', 'c']
|
||||
sum({1,2})
|
||||
3
|
||||
sum([1,2,3])
|
||||
6
|
||||
sum(x for x in range(1, 6))
|
||||
15
|
||||
sum([1,2,3,4,5],5)
|
||||
20
|
||||
#1+2+3+4+5+5
|
||||
sum([2.1,2.1])
|
||||
4.2
|
||||
```
|
||||
- Функция zip, попробовал применить к list, dict
|
||||
```py
|
||||
zip([1,2,3],['a','b','c'])
|
||||
<zip object at 0x105905bc0>
|
||||
list(zip([1,2,3],['a','b','c']))
|
||||
[(1, 'a'), (2, 'b'), (3, 'c')]
|
||||
list(zip([5,5,5],['a','b']))
|
||||
[(5, 'a'), (5, 'b')]
|
||||
a = {'b': 2, 'a': 1, 'c': 3}
|
||||
a
|
||||
{'b': 2, 'a': 1, 'c': 3}
|
||||
type(a)
|
||||
<class 'dict'>
|
||||
key = [1,2,5]
|
||||
values = ['a','v','c']
|
||||
dc = dict(zip(key,values))
|
||||
dc
|
||||
{1: 'a', 2: 'v', 5: 'c'}
|
||||
```
|
||||
|
||||
### 6.Удостоверился, что регистр отличается
|
||||
```py
|
||||
Gg1=45
|
||||
gg1=1.6
|
||||
gg1
|
||||
1.6
|
||||
Gg1
|
||||
45
|
||||
```
|
||||
|
||||
### 7.Примение простоых базовых типов
|
||||
#### 7.1 Логический тип
|
||||
```py
|
||||
bb1=True; bb2=False
|
||||
bb1;bb2
|
||||
True
|
||||
False
|
||||
type(bb1)
|
||||
<class 'bool'>
|
||||
```
|
||||
|
||||
#### 7.2 Переменные с целочисленным,вещественным и комплексным типами
|
||||
```py
|
||||
ii1=-1234567890
|
||||
ff1=-8.9876e-12
|
||||
type(ii1)
|
||||
<class 'int'>
|
||||
type(ff1)
|
||||
<class 'float'>
|
||||
cc1=2-3j
|
||||
type(cc1)
|
||||
<class 'complex'>
|
||||
a=3.67; b=-0.45
|
||||
cc2 = complex(a,b)
|
||||
cc2
|
||||
(3.67-0.45j)
|
||||
type(cc1)
|
||||
<class 'complex'>
|
||||
type(cc2)
|
||||
<class 'complex'>
|
||||
```
|
||||
- Проверил в каком классе сохранилось двочиное, восьмеричное, шестнадцатеричное число
|
||||
```py
|
||||
dv1=0b1101010
|
||||
type(dv1)
|
||||
<class 'int'>
|
||||
vsm1=0o52765
|
||||
type(vsm1)
|
||||
<class 'int'>
|
||||
shest1=0x7109af6
|
||||
type(shest1)
|
||||
<class 'int'>
|
||||
```
|
||||
#### 7.3 Изучаю тип переменной - строка
|
||||
```py
|
||||
ss1='Это - строка символов'
|
||||
ss1="Это - строка символов"
|
||||
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
|
||||
ss1a
|
||||
'Это - " строка символов ", \n \t выводимая на двух строках'
|
||||
print(ss1a)
|
||||
Это - " строка символов ",
|
||||
выводимая на двух строках
|
||||
ss1b = 'Меня зовут: \nАнтонов Д.А'
|
||||
print(ss1b)
|
||||
Меня зовут:
|
||||
Антонов Д.А
|
||||
mnogo="""Нетрудно заметить , что в результате операции над числами разных типов получается число,имеющее более сложный тип из тех, которые участвуют в операции."""
|
||||
print(mnogo)
|
||||
Нетрудно заметить , что в результате операции над числами разных типов получается число,имеющее более сложный тип из тех, которые участвуют в операции.
|
||||
```
|
||||
- Изучаю как получить доступ к символам строки
|
||||
```py
|
||||
ss1[0]
|
||||
'Э'
|
||||
ss1[8]
|
||||
'р'
|
||||
ss1[-2]
|
||||
'о'
|
||||
ss1[6:9]
|
||||
'стр'
|
||||
ss1
|
||||
'Это - строка символов'
|
||||
ss1[20]
|
||||
'в'
|
||||
ss1[21]
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#50>", line 1, in <module>
|
||||
ss1[21]
|
||||
IndexError: string index out of range
|
||||
```
|
||||
- Применяю различные варианты «разрезания» или «создания среза»
|
||||
```py
|
||||
ss1[13:]
|
||||
'символов'
|
||||
ss1[:13]
|
||||
'Это - строка '
|
||||
ss1[5:-8]
|
||||
' строка '
|
||||
ss1[3:17:2]
|
||||
' тоасм'
|
||||
ss1[0]
|
||||
'Э'
|
||||
ss1[17:3:-2]
|
||||
'омсаот '
|
||||
ss1[17:3:-1]
|
||||
'овмис акортс -'
|
||||
ss1[-4:3:-2]
|
||||
'омсаот '
|
||||
ss1[4]='='
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#60>", line 1, in <module>
|
||||
ss1[4]='='
|
||||
TypeError: 'str' object does not support item assignment
|
||||
ss1=ss1[:4]+'='+ss1[5:]
|
||||
ss1
|
||||
'Это = строка символов'
|
||||
ss1b
|
||||
'Меня зовут: \nАнтонов Д.А'
|
||||
ss1b[3]
|
||||
'я'
|
||||
ss1b[3-1]
|
||||
'н'
|
||||
ss1b[-3]
|
||||
'Д'
|
||||
ss1b[-3:]
|
||||
'Д.А'
|
||||
ss1b[:-3]
|
||||
'Меня зовут: \nАнтонов '
|
||||
ss1b[0:]
|
||||
'Меня зовут: \nАнтонов Д.А'
|
||||
ss1b[0:-1]
|
||||
'Меня зовут: \nАнтонов Д.'
|
||||
ss1b[0:0]
|
||||
''
|
||||
ss1b[5:-5]
|
||||
'зовут: \nАнтоно'
|
||||
ss1b[-23:0]
|
||||
''
|
||||
ss1b[0:23:-1]
|
||||
''
|
||||
ss1b[0:23:1]
|
||||
'Меня зовут: \nАнтонов Д.'
|
||||
ss1b[24:0:-1]
|
||||
'А.Д вонотнА\n :тувоз яне'
|
||||
ss1b[24:0:-2]
|
||||
'АДвнтА твзяе'
|
||||
ss1b[24:-2:-2]
|
||||
'А'
|
||||
ss1b[24:0:-2]
|
||||
'АДвнтА твзяе'
|
||||
ss1b[24:0:-1]
|
||||
'А.Д вонотнА\n :тувоз яне'
|
||||
ss1b[24::-1]
|
||||
'А.Д вонотнА\n :тувоз янеМ'
|
||||
ss1b[None:None:-1]
|
||||
'А.Д вонотнА\n :тувоз янеМ'
|
||||
ss1b=ss1b[0:5] + "-" + ss1b[6:None]
|
||||
ss1b
|
||||
'Меня -овут: \nАнтонов Д.А'
|
||||
```
|
||||
#### 7.4 Выполеняю задание, самостоятельно закрпляю изученные типы переменных
|
||||
```py
|
||||
stringg = '12'+"ab"
|
||||
type(stringg)
|
||||
<class 'str'>
|
||||
a = 100
|
||||
type(a)
|
||||
<class 'int'>
|
||||
b = 0-1j
|
||||
type(b)
|
||||
<class 'complex'>
|
||||
b=0.1
|
||||
type(b)
|
||||
<class 'float'>
|
||||
b = 0.001200
|
||||
type(b)
|
||||
<class 'float'>
|
||||
b = 0.1e-100
|
||||
type(b)
|
||||
<class 'float'>
|
||||
c = 0-1j
|
||||
type(c)
|
||||
<class 'complex'>
|
||||
var = c/b
|
||||
type(var)
|
||||
<class 'complex'>
|
||||
b = True
|
||||
type(b)
|
||||
<class 'bool'>
|
||||
b = None
|
||||
type(b)
|
||||
<class 'NoneType'>
|
||||
```
|
||||
|
||||
### 8. Сложные типы объектов
|
||||
|
||||
#### 8.1 Списки
|
||||
|
||||
- Начало работы со списками
|
||||
```py
|
||||
spis1 = [111,'Spisok',5-9j]
|
||||
stup=[0,0,1,1,1,1,1,1,1]
|
||||
spis = [1,2,3,4
|
||||
,5,6,7
|
||||
,8,9,10]
|
||||
spis
|
||||
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
spis1[-1]
|
||||
(5-9j)
|
||||
stup[-8::2]
|
||||
[0, 1, 1, 1]
|
||||
stup[-8:None:2]
|
||||
[0, 1, 1, 1]
|
||||
|
||||
#Сколько элементов вошло в этот новый список и какие индексы они имели в исходном списке?
|
||||
len(stup[-8:None:2])
|
||||
4
|
||||
#4 элемента вошло, индексы - 1 3 5 7
|
||||
|
||||
spis1[1]='Список'
|
||||
spis1
|
||||
[111, 'Список', (5-9j)]
|
||||
len(spis1)
|
||||
3
|
||||
```
|
||||
- Изучил доступные методы для списков
|
||||
```py
|
||||
dir()
|
||||
|
||||
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os', 'spis', 'spis1', 'stup']
|
||||
dir(spis1)
|
||||
|
||||
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
|
||||
dir(spis1.append)
|
||||
|
||||
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
|
||||
```
|
||||
- Пробую методы добавления и удаления элемента в списке
|
||||
```py
|
||||
spis1.append('New Item')
|
||||
print(spis1)
|
||||
[111, 'Список', (5-9j), 'New Item']
|
||||
spis1+['New Item'] #НОВЫЙ ЭЛЕМЕНТ НЕ СОЗДАЛСЯ
|
||||
[111, 'Список', (5-9j), 'New Item', 'New Item']
|
||||
print(spis1)
|
||||
[111, 'Список', (5-9j), 'New Item']
|
||||
spis1+=['New Item']
|
||||
print(spis1)
|
||||
[111, 'Список', (5-9j), 'New Item', 'New Item']
|
||||
ss1b = 'Меня зовут: \n Антонов Д.А'
|
||||
spis1.append(ss1b)
|
||||
print(spis1)
|
||||
[111, 'Список', (5-9j), 'New Item', 'New Item', 'Меня зовут: \n Антонов Д.А']
|
||||
spis1.pop()
|
||||
'Меня зовут: \n Антонов Д.А'
|
||||
print(spis1)
|
||||
[111, 'Список', (5-9j), 'New Item', 'New Item']
|
||||
spis1.pop(0)
|
||||
111
|
||||
print(spis1)
|
||||
['Список', (5-9j), 'New Item', 'New Item']
|
||||
```
|
||||
- Добавляю и удаляю элементы списока через методы insert и remove
|
||||
```py
|
||||
spis1.insert(0,"insert to start")
|
||||
print(spis1)
|
||||
['insert to start', 'Список', (5-9j), 'New Item', 'New Item']
|
||||
spis1.insert(len(spis1),"insert to end")
|
||||
print(spis1)
|
||||
['insert to start', 'Список', (5-9j), 'New Item', 'New Item', 'insert to end']
|
||||
spis1.pop(4)
|
||||
'New Item'
|
||||
spis1.insert(int(len(spis1)/2),"insert to middle")
|
||||
print(spis1)
|
||||
['insert to start', 'Список', 'insert to middle', (5-9j), 'New Item', 'insert to end']
|
||||
spis1.append('Список')
|
||||
print(spis1)
|
||||
['insert to start', 'Список', 'insert to middle', (5-9j), 'New Item', 'insert to end', 'Список']
|
||||
spis1.remove("Список")
|
||||
print(spis1)
|
||||
['insert to start', 'insert to middle', (5-9j), 'New Item', 'insert to end', 'Список']
|
||||
```
|
||||
- Пробую методы extend и clear
|
||||
```py
|
||||
spis2 = ['n','e','w']
|
||||
print(spis2)
|
||||
['n', 'e', 'w']
|
||||
spis1.extend(spis2)
|
||||
print(spis1)
|
||||
['insert to start', 'insert to middle', (5-9j), 'New Item', 'insert to end', 'Список', 'n', 'e', 'w']
|
||||
spis1.append(spis2)
|
||||
print(spis1)
|
||||
['insert to start', 'insert to middle', (5-9j), 'New Item', 'insert to end', 'Список', 'n', 'e', 'w', ['n', 'e', 'w']] #главное отличие от extend, добавился список элементов, но не по отдельности каждый элемен
|
||||
spis2.clear()
|
||||
print(spis2)
|
||||
[]
|
||||
```
|
||||
- Изучаю метод sort для списка
|
||||
```py
|
||||
spis1.sort()
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#65>", line 1, in <module>
|
||||
spis1.sort()
|
||||
TypeError: '<' not supported between instances of 'complex' and 'str'
|
||||
spis2 = [0,2,-1,3,-2,100,-1,4,5,9,2]
|
||||
spis2.sort()
|
||||
print(spis2)
|
||||
[-2, -1, -1, 0, 2, 2, 3, 4, 5, 9, 100]
|
||||
spis2 = [0,2,-1,3,-2,100,-1,4,5,9,2]
|
||||
spis2.sort(reverse=True)
|
||||
print(spis2)
|
||||
[100, 9, 5, 4, 3, 2, 2, 0, -1, -1, -2]
|
||||
spis2 = ['B','a','c']
|
||||
spis2.sort()
|
||||
print(spis2)
|
||||
['B', 'a', 'c']
|
||||
spis2 = ['B','a','c']
|
||||
spis2.sort(key=str.lower)
|
||||
print(spis2)
|
||||
['a', 'B', 'c']
|
||||
```
|
||||
- Пробую методы reverse, count и copy
|
||||
```py
|
||||
spis2.reverse()
|
||||
print(spis2)
|
||||
['c', 'B', 'a']
|
||||
a = [1,2,3,4,5]
|
||||
b = a
|
||||
b.append(4)
|
||||
print(a)
|
||||
[1, 2, 3, 4, 5, 4]
|
||||
c = a.copy()
|
||||
print(c)
|
||||
[1, 2, 3, 4, 5, 4]
|
||||
a.append(9)
|
||||
print(c)
|
||||
[1, 2, 3, 4, 5, 4]
|
||||
print(a)
|
||||
[1, 2, 3, 4, 5, 4, 9]
|
||||
a.count(1)
|
||||
1
|
||||
a.count(-1)
|
||||
0
|
||||
a.append(1)
|
||||
a.count(1)
|
||||
2
|
||||
a.index(1)
|
||||
0
|
||||
print(a)
|
||||
[1, 2, 3, 4, 5, 4, 9, 1]
|
||||
a.index(11)
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#117>", line 1, in <module>
|
||||
a.index(11)
|
||||
ValueError: 11 is not in list
|
||||
```
|
||||
- Создаю вложенный список и пробую менять значения элементов
|
||||
```py
|
||||
spis2=[spis1,[4,5,6,7]]
|
||||
print(spis2)
|
||||
[['insert to start', 'insert to middle', (5-9j), 'New Item', 'insert to end', 'Список', 'n', 'e', 'w', []], [4, 5, 6, 7]]
|
||||
spis2[0][1]=78
|
||||
print(spis2)
|
||||
[['insert to start', 78, (5-9j), 'New Item', 'insert to end', 'Список', 'n', 'e', 'w', []], [4, 5, 6, 7]]
|
||||
spis1
|
||||
['insert to start', 78, (5-9j), 'New Item', 'insert to end', 'Список', 'n', 'e', 'w', []]
|
||||
#использутся одна область памяти. При содании нового списка, ему присваивается сслыка на исходный объект
|
||||
a = [1, 2, 3, 4, 5, 4, 9, 1]
|
||||
b = [a.copy(),[11,55,555]]
|
||||
b[0][0] = 999
|
||||
b
|
||||
[[999, 2, 3, 4, 5, 4, 9, 1], [11, 55, 555]]
|
||||
a
|
||||
[1, 2, 3, 4, 5, 4, 9, 1]
|
||||
my_list_obj = [5,'Лабораторная работа',True,False,[b.copy()]]
|
||||
print(my_list_obj)
|
||||
[5, 'Лабораторная работа', True, False, [[[999, 2, 3, 4, 5, 4, 9, 1], [11, 55, 555]]]]
|
||||
```
|
||||
append() добавляет весь объект как один элемент.
|
||||
extend() добавляет каждый элемент итерируемого объекта отдельно.
|
||||
|
||||
#### 8.2 Объект-кортеж
|
||||
- Начало работы, создаю кортеж
|
||||
```py
|
||||
kort1=(222,'Kortezh',77+8j)
|
||||
kort1 = kort1+(1,2)
|
||||
kort1
|
||||
(222, 'Kortezh', (77+8j), 1, 2)
|
||||
kort1= kort1+(ss1b,)
|
||||
kort1
|
||||
(222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут: \n Антонов Д.А')
|
||||
kort2 = kort1[:2]+kort1[3:]
|
||||
kort2
|
||||
(222, 'Kortezh', 1, 2, 'Меня зовут: \n Антонов Д.А')
|
||||
```
|
||||
- Использую допустимые методы для кортежа
|
||||
```py
|
||||
dir(kort2)
|
||||
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
|
||||
kort1.index(2)
|
||||
4
|
||||
kort1.index(222)
|
||||
0
|
||||
kort1.count(222)
|
||||
1
|
||||
```
|
||||
- Удостоверился, что кортеж нельзя изменить
|
||||
```py
|
||||
kort1[2]=90
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#156>", line 1, in <module>
|
||||
kort1[2]=90
|
||||
TypeError: 'tuple' object does not support item assignment
|
||||
```
|
||||
- Создаю свой кортеж
|
||||
```py
|
||||
my_tuple = (5,"my tuple for lab", ["list","in","tuplre"],(555,444))
|
||||
type(my_tuple)
|
||||
<class 'tuple'>
|
||||
print(my_tuple)
|
||||
(5, 'my tuple for lab', ['list', 'in', 'tuplre'], (555, 444))
|
||||
my_tuple[2]
|
||||
['list', 'in', 'tuplre']
|
||||
type(my_tuple[3])
|
||||
<class 'tuple'>
|
||||
```
|
||||
|
||||
#### 8.3 Объект-словарь
|
||||
|
||||
- Начало работы со словарем
|
||||
```py
|
||||
dic1={'Saratov':145, 'Orel':56, 'Vologda':45}
|
||||
dic1['Orel']
|
||||
56
|
||||
dic1['Pskov']=78
|
||||
dic1
|
||||
{'Saratov': 145, 'Orel': 56, 'Vologda': 45, 'Pskov': 78}
|
||||
```
|
||||
- Выделение ключей и значений, сортировка словаря
|
||||
```py
|
||||
dic1.keys()
|
||||
dict_keys(['Saratov', 'Orel', 'Vologda', 'Pskov'])
|
||||
```
|
||||
- Нельзя использовать sort (in-place сортировка). Так как для сортировки словаря создается новый объяект
|
||||
```py
|
||||
sort(dic1.keys())
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#169>", line 1, in <module>
|
||||
sort(dic1.keys())
|
||||
NameError: name 'sort' is not defined. Did you mean: 'kort1'?
|
||||
```
|
||||
- Изучаю сортировку словарей и доступ к элментам
|
||||
```py
|
||||
sorted(dic1.keys())
|
||||
['Orel', 'Pskov', 'Saratov', 'Vologda']
|
||||
sorted(dic1.values())
|
||||
[45, 56, 78, 145]
|
||||
dic2={1:'mean',2:'standart deviation',3:'correlation'}
|
||||
dic3={'statistics':dic2,'POAS':['base','elementary','programming']}
|
||||
dic3['statistics'][2]
|
||||
'standart deviation'
|
||||
dic3['statistics'][3]
|
||||
'correlation'
|
||||
```
|
||||
- Создаю словари разными способами (dict,zip,{}) и с разными типами ключей/значений
|
||||
```py
|
||||
dic4=dict([(1,['A','B','C']),(2,[4,5]),('Q','Prim'),('Stroka',ss1b)])
|
||||
dic4
|
||||
{1: ['A', 'B', 'C'], 2: [4, 5], 'Q': 'Prim', 'Stroka': 'Меня зовут: \n Антонов Д.А'}
|
||||
dic4={1:['A','B','C'],2:[4,5],'Q': 'Prim','Stroka': ss1b}
|
||||
dic4
|
||||
{1: ['A', 'B', 'C'], 2: [4, 5], 'Q': 'Prim', 'Stroka': 'Меня зовут: \n Антонов Д.А'}
|
||||
dic5 = dict([(1,2),(2,4)])
|
||||
dic5
|
||||
{1: 2, 2: 4}
|
||||
dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b]))
|
||||
dic5
|
||||
{'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут: \n Антонов Д.А'}
|
||||
```
|
||||
- Создаю словарь самостоятельно
|
||||
```py
|
||||
my_tuple = (1,2,3,4,5,6,7)
|
||||
type(my_tuple)
|
||||
<class 'tuple'>
|
||||
my_list = ['сова','ворона','волк','лиса','носорог']
|
||||
my_dict = dict(zip(my_tuple,my_list))
|
||||
my_dict
|
||||
{1: 'сова', 2: 'ворона', 3: 'волк', 4: 'лиса', 5: 'носорог'}
|
||||
```
|
||||
- Размер равен 5 так как выбирается наименьшая длина из всех длин объектов
|
||||
```py
|
||||
len(my_dict)
|
||||
5
|
||||
```
|
||||
- Пробую доступ к словарю
|
||||
```py
|
||||
AVTI={'Курс I':[22,23,17,24,30,29,28,25,23,0,4,31,30,33,18,12,27],'Курс II':[18,16,12,15,29,18,21,23,13,0,4,20,31,26,16,], 'Курс III':[17,12,0,6,17,15,19,19,0,0,5,17,22,18,12], 'Курс IV':[27,16,0,13,17,15,19,20,0,0,2,15,18,16,17]}
|
||||
AVTI['Курс III'][5]
|
||||
15
|
||||
AVTI['Курс I'][len(AVTI)]
|
||||
30
|
||||
```
|
||||
|
||||
#### 8.4 Изучаю объект-множество
|
||||
|
||||
- Начало работы, создаю множество
|
||||
```py
|
||||
mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
|
||||
mnoz1
|
||||
{'датчик', 'двигатель', 'микропроцессор', 'линия связи'}
|
||||
```
|
||||
- Нвблюдаю, что при выводе элементов множества, они становятся неупорядочеными
|
||||
```py
|
||||
p = {'b','c','a'}
|
||||
p
|
||||
{'b', 'a', 'c'}
|
||||
```
|
||||
- Применяю стандратные методы к множеству
|
||||
```py
|
||||
len(mnoz1)
|
||||
4
|
||||
'датчик' in mnoz1
|
||||
True
|
||||
mnoz1.add('реле')
|
||||
mnoz1
|
||||
{'датчик', 'микропроцессор', 'линия связи', 'двигатель', 'реле'}
|
||||
mnoz1.remove('линия связи')
|
||||
mnoz1
|
||||
{'датчик', 'микропроцессор', 'двигатель', 'реле'}
|
||||
mnoz1.remove('реле')
|
||||
mnoz1
|
||||
{'датчик', 'микропроцессор', 'двигатель'}
|
||||
```
|
||||
- Проверил и попробовал разные доступные операции множества
|
||||
```py
|
||||
dir(mnoz1)
|
||||
['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
|
||||
mnoz1.pop()
|
||||
'датчик'
|
||||
mnoz1
|
||||
{'микропроцессор', 'двигатель'}
|
||||
mnoz1.pop()
|
||||
'микропроцессор'
|
||||
mnoz1
|
||||
{'двигатель'}
|
||||
```
|
||||
- Выполняю задание, придумал свой объект-множество
|
||||
```py
|
||||
my_set = {'строка в множестве',0.5,535,(5,6,7,'лабораторная')} #нельзя использовать list/dict - unhashable
|
||||
my_set
|
||||
{0.5, (5, 6, 7, 'лабораторная'), 'строка в множестве', 535}
|
||||
```
|
||||
- Пробую доступные операции с множеством
|
||||
```py
|
||||
my_set.add('POAC')
|
||||
my_set
|
||||
{0.5, 'POAC', 'строка в множестве', 535, (5, 6, 7, 'лабораторная')}
|
||||
my_set.remove(0.5)
|
||||
my_set
|
||||
{'POAC', 'строка в множестве', 535, (5, 6, 7, 'лабораторная')}
|
||||
my_set.pop()
|
||||
'POAC'
|
||||
'строка в множестве' in my_set
|
||||
True
|
||||
'строка' in my_set
|
||||
False
|
||||
len(my_set)
|
||||
3
|
||||
new = my_set.copy()
|
||||
new
|
||||
{'строка в множестве', (5, 6, 7, 'лабораторная'), 535}
|
||||
new.pop()
|
||||
'строка в множестве'
|
||||
new
|
||||
{(5, 6, 7, 'лабораторная'), 535}
|
||||
my_set
|
||||
{'строка в множестве', 535, (5, 6, 7, 'лабораторная')}
|
||||
new.clear()
|
||||
new
|
||||
set()
|
||||
new.add(535)
|
||||
inter_set = my_set.intersection(new,my_set)
|
||||
inter_set
|
||||
{535}
|
||||
inter_set = new.intersection(new,my_set)
|
||||
inter_set
|
||||
{535}
|
||||
```
|
@ -1,98 +0,0 @@
|
||||
# Общее контрольное задание по теме 2
|
||||
|
||||
**Антонов Дмитрий, А-03-23**
|
||||
|
||||
## Задание
|
||||
Реализовать, записать в текстовый файл и проанализировать результаты последовательности инструкций, выполняющих следующие действия
|
||||
1. Создать переменную с именем familia и со значением - символьной строкой – своей фамили-ей в латинской транскрипции.
|
||||
2. Создать переменную со значением, совпадающим с первой буквой из familia.
|
||||
3. Создать переменную с именем sp_kw со значением – списком всей ключевых слов языка Python.
|
||||
4. Удалите из списка sp_kw значение 'nonlocal'. Выводом списка в командном окне IDLE убедитесь, что это значение удалено из списка.
|
||||
5. Создайте кортеж kort_nam с именами: вашим и еще 3-х студентов из вашей группы. Напишите инструкцию, позволяющую убедиться, что тип переменной – это tuple.
|
||||
6. Напишите инструкцию, добавляющую в kort_nam имена еще двух студентов.
|
||||
7. Напишите инструкцию, позволяющую определить, сколько раз в кортеже присутствуют студенты с именем «Дима».
|
||||
8. Создайте словарь dict_bas, в котором ключами являются русские названия типов переменных, использованных в предыдущих операторах, а значениями – ранее созданные перемен-ные, соответствующие этим типам.
|
||||
## Решение
|
||||
#### 1. Создаю переменную familia.
|
||||
```py
|
||||
familia = 'Antonov'
|
||||
type(familia)
|
||||
<class 'str'>
|
||||
```
|
||||
|
||||
#### 2. Создаю переменную, которая равна первой букве familia.
|
||||
```py
|
||||
var = 'A'
|
||||
var = familia[0]
|
||||
```
|
||||
#### 3. Создаю переменную с именем sp_kw, значение – списк всех ключевых слов Python.
|
||||
```py
|
||||
import keyword
|
||||
dir(keyword)
|
||||
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'iskeyword', 'issoftkeyword', 'kwlist', 'softkwlist']
|
||||
```
|
||||
- Импортивал библиотеку, проверил доступные методы
|
||||
```py
|
||||
sp_kw = keyword.kwlist
|
||||
type(sp_kw)
|
||||
<class 'list'>
|
||||
```
|
||||
- Проверил тип переменной
|
||||
```py
|
||||
print(sp_kw)
|
||||
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
|
||||
```
|
||||
#### 4. Удаляю из списка sp_kw значение 'nonlocal', затем убедился, что это значение удалено из списка.
|
||||
```py
|
||||
sp_kw.remove('nonlocal')
|
||||
print(sp_kw)
|
||||
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
|
||||
```
|
||||
- После физической проверки дополнительно убедился в отсутствии 'nonlocal' программно
|
||||
```py
|
||||
'nonlocal' in sp_kw
|
||||
False
|
||||
```
|
||||
#### 5. Создаю кортеж kort_nam с моим и еще 3-х студентов из группы именами. Проверяю, что тип переменной – это tuple.
|
||||
```py
|
||||
kort_nam = ('Дмитрий','Артем','Александр','Максим')
|
||||
type(kort_nam)
|
||||
<class 'tuple'>
|
||||
```
|
||||
#### 6. Добавляю в kort_nam имена двух студентов.
|
||||
```py
|
||||
kort_nam = kort_nam + ('Иван','Людмила')
|
||||
kort_nam
|
||||
('Дмитрий', 'Артем', 'Александр', 'Максим', 'Иван', 'Людмила')
|
||||
```
|
||||
- Использовал переопределение, убедился в добавлении слов с помощью вывода
|
||||
|
||||
#### 7. Определяю, сколько раз в кортеже присутствуют студенты с именем «Дима».
|
||||
```py
|
||||
dir(kort_nam)
|
||||
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
|
||||
```
|
||||
- Проверил доступные методы
|
||||
```py
|
||||
kort_nam.count('Дима')
|
||||
0
|
||||
```
|
||||
#### 8. Создаю словарь dict_bas, в котором ключами являются русские названия типов переменных, использованных в предыдущих операторах, а значениями – ранее созданные перемен-ные, соответствующие этим типам.
|
||||
```py
|
||||
dict_bas = {'строка': [familia,var],'список': sp_kw,'кортеж': kort_nam}
|
||||
print(dict_bas)
|
||||
{'строка': ['Antonov', 'A'], 'список': ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'], 'кортеж': ('Дмитрий', 'Артем', 'Александр', 'Максим', 'Иван', 'Людмила')}
|
||||
dict_bas.keys()
|
||||
dict_keys(['строка', 'список', 'кортеж'])
|
||||
dict_bas.values()
|
||||
dict_values([['Antonov', 'A'], ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'], ('Дмитрий', 'Артем', 'Александр', 'Максим', 'Иван', 'Людмила')])
|
||||
```
|
||||
- Создал и вывел словарь, а также ключи и значения отдельно
|
||||
```py
|
||||
dict_bas = dict([('строка',[familia,var]),('список',sp_kw),('кортеж',kort_nam)])
|
||||
dict_bas
|
||||
{'строка': ['Antonov', 'A'], 'список': ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'], 'кортеж': ('Дмитрий', 'Артем', 'Александр', 'Максим', 'Иван', 'Людмила')}
|
||||
```
|
||||
- Создал словарь иным способом, затем вывел
|
||||
|
||||
|
Загрузка…
Ссылка в новой задаче