форкнуто от main/python-labs
Родитель
40b266c73e
Сommit
18188545be
@ -0,0 +1,744 @@
|
|||||||
|
# Отчёт по Теме 2 Ходюк Максим Романович
|
||||||
|
|
||||||
|
## Пункт 1
|
||||||
|
Запустил оболочку IDLE
|
||||||
|
|
||||||
|
## Пункт 2
|
||||||
|
Изучил простые объекты
|
||||||
|
Создал переменные f1 f2 и присвоил им значения
|
||||||
|
```
|
||||||
|
f1=16; f2=3
|
||||||
|
```
|
||||||
|
Посмотрел значения созданных переменных двумя способами
|
||||||
|
```
|
||||||
|
f1,f2
|
||||||
|
(16, 3)
|
||||||
|
f1;f2
|
||||||
|
16
|
||||||
|
3
|
||||||
|
```
|
||||||
|
|
||||||
|
Использовал функцию dir, чтобы узнать, какие обьекты существуют в данный момент в среде
|
||||||
|
```
|
||||||
|
dir()
|
||||||
|
['annotations', 'builtins', 'doc', 'loader', 'name', 'package',
|
||||||
|
'spec', 'f1', 'f2']
|
||||||
|
```
|
||||||
|
|
||||||
|
Та же функция используется для получения списка атрибутов любого объекта
|
||||||
|
```
|
||||||
|
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']
|
||||||
|
```
|
||||||
|
|
||||||
|
Посмотрел классовую принадлежность ранее созданной переменной f2
|
||||||
|
```
|
||||||
|
type(f2)
|
||||||
|
<class 'int'>
|
||||||
|
```
|
||||||
|
|
||||||
|
Удалил объекты с помощью функции del и убедился, что объектов больше нет в памяти
|
||||||
|
```
|
||||||
|
del f1,f2
|
||||||
|
dir()
|
||||||
|
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
|
||||||
|
```
|
||||||
|
|
||||||
|
## Пункт 3
|
||||||
|
Изучение правил именования объектов
|
||||||
|
Задал значение в виде вещественного числа:
|
||||||
|
```
|
||||||
|
gg1=1.6
|
||||||
|
```
|
||||||
|
Задал значение в виде символьной строки
|
||||||
|
```
|
||||||
|
hh1='Строка'
|
||||||
|
```
|
||||||
|
Попробовал задать объект с недопустимым именем-начинается с цифры:
|
||||||
|
```
|
||||||
|
73sr=3
|
||||||
|
SyntaxError: invalid decimal literal
|
||||||
|
```
|
||||||
|
Программа выдала ошибку
|
||||||
|
|
||||||
|
Попробовал задать объект с именем, которое совпадает с ключевым словом - программа снова выдала ошибку
|
||||||
|
```
|
||||||
|
and=7
|
||||||
|
SyntaxError: invalid syntax
|
||||||
|
```
|
||||||
|
|
||||||
|
## Пункт 4
|
||||||
|
Вывел список ключевых слов с помощью инструкции:
|
||||||
|
```
|
||||||
|
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']
|
||||||
|
```
|
||||||
|
Cохранил выведенный список в отдельную переменную
|
||||||
|
```
|
||||||
|
SpisKeyword=keyword.kwlist
|
||||||
|
SpisKeyword
|
||||||
|
['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']
|
||||||
|
```
|
||||||
|
|
||||||
|
## Пункт 5
|
||||||
|
Вывел список встроенных идентификаторов с помощью инструкций:
|
||||||
|
```
|
||||||
|
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', 'WindowsError', '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']
|
||||||
|
```
|
||||||
|
|
||||||
|
Самостоятельно изучил назначение и применил некоторые из встроенных функций
|
||||||
|
```
|
||||||
|
help(abs)
|
||||||
|
Help on built-in function abs in module builtins:
|
||||||
|
|
||||||
|
abs(x, /)
|
||||||
|
Return the absolute value of the argument.
|
||||||
|
|
||||||
|
help(len)
|
||||||
|
Help on built-in function len in module builtins:
|
||||||
|
|
||||||
|
len(obj, /)
|
||||||
|
Return the number of items in a container.
|
||||||
|
|
||||||
|
help(max)
|
||||||
|
Help on built-in function max in module builtins:
|
||||||
|
|
||||||
|
max(...)
|
||||||
|
max(iterable, *[, default=obj, key=func]) -> value
|
||||||
|
max(arg1, arg2, *args, *[, key=func]) -> value
|
||||||
|
|
||||||
|
With a single iterable argument, return its biggest item. The
|
||||||
|
default keyword-only argument specifies an object to return if
|
||||||
|
the provided iterable is empty.
|
||||||
|
With two or more positional arguments, return the largest argument.
|
||||||
|
|
||||||
|
help(min)
|
||||||
|
Help on built-in function min in module builtins:
|
||||||
|
|
||||||
|
min(...)
|
||||||
|
min(iterable, *[, default=obj, key=func]) -> value
|
||||||
|
min(arg1, arg2, *args, *[, key=func]) -> value
|
||||||
|
|
||||||
|
With a single iterable argument, return its smallest item. The
|
||||||
|
default keyword-only argument specifies an object to return if
|
||||||
|
the provided iterable is empty.
|
||||||
|
With two or more positional arguments, return the smallest argument.
|
||||||
|
|
||||||
|
help(pow)
|
||||||
|
Help on built-in function pow in module builtins:
|
||||||
|
|
||||||
|
pow(base, exp, mod=None)
|
||||||
|
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
|
||||||
|
|
||||||
|
Some types, such as ints, are able to use a more efficient algorithm when
|
||||||
|
invoked using the three argument form.
|
||||||
|
|
||||||
|
help(round)
|
||||||
|
Help on built-in function round in module builtins:
|
||||||
|
|
||||||
|
round(number, ndigits=None)
|
||||||
|
Round a number to a given precision in decimal digits.
|
||||||
|
|
||||||
|
The return value is an integer if ndigits is omitted or None. Otherwise
|
||||||
|
the return value has the same type as the number. ndigits may be negative.
|
||||||
|
|
||||||
|
help(sorted)
|
||||||
|
Help on built-in function sorted in module builtins:
|
||||||
|
|
||||||
|
sorted(iterable, /, *, key=None, reverse=False)
|
||||||
|
Return a new list containing all items from the iterable in ascending order.
|
||||||
|
|
||||||
|
A custom key function can be supplied to customize the sort order, and the
|
||||||
|
reverse flag can be set to request the result in descending order.
|
||||||
|
|
||||||
|
help(sum)
|
||||||
|
Help on built-in function sum in module builtins:
|
||||||
|
|
||||||
|
sum(iterable, /, start=0)
|
||||||
|
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
|
||||||
|
|
||||||
|
When the iterable is empty, return the start value.
|
||||||
|
This function is intended specifically for use with numeric values and may
|
||||||
|
reject non-numeric types.
|
||||||
|
|
||||||
|
help(zip)
|
||||||
|
Help on class zip in module builtins:
|
||||||
|
|
||||||
|
class zip(object)
|
||||||
|
| zip(*iterables, strict=False)
|
||||||
|
|
|
||||||
|
| The zip object yields n-length tuples, where n is the number of iterables
|
||||||
|
| passed as positional arguments to zip(). The i-th element in every tuple
|
||||||
|
| comes from the i-th iterable argument to zip(). This continues until the
|
||||||
|
| shortest argument is exhausted.
|
||||||
|
|
|
||||||
|
| If strict is true and one of the arguments is exhausted before the others,
|
||||||
|
| raise a ValueError.
|
||||||
|
|
|
||||||
|
| >>> list(zip('abcdefg', range(3), range(4)))
|
||||||
|
| [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
|
||||||
|
|
|
||||||
|
| Methods defined here:
|
||||||
|
|
|
||||||
|
| __getattribute__(self, name, /)
|
||||||
|
| Return getattr(self, name).
|
||||||
|
|
|
||||||
|
| __iter__(self, /)
|
||||||
|
| Implement iter(self).
|
||||||
|
|
|
||||||
|
| __next__(self, /)
|
||||||
|
| Implement next(self).
|
||||||
|
|
|
||||||
|
| __reduce__(self, /)
|
||||||
|
| Return state information for pickling.
|
||||||
|
|
|
||||||
|
| __setstate__(self, object, /)
|
||||||
|
| Set state information for unpickling.
|
||||||
|
|
|
||||||
|
| ----------------------------------------------------------------------
|
||||||
|
| Static methods defined here:
|
||||||
|
|
|
||||||
|
| __new__(*args, **kwargs)
|
||||||
|
| Create and return a new object. See help(type) for accurate signature.
|
||||||
|
abs(-25)
|
||||||
|
25
|
||||||
|
len(SpisKeyword)
|
||||||
|
35
|
||||||
|
max(24,26,91,12341)
|
||||||
|
12341
|
||||||
|
min(12,-14,241,2)
|
||||||
|
-14
|
||||||
|
pow(2,4)
|
||||||
|
16
|
||||||
|
round(2.4231)
|
||||||
|
2
|
||||||
|
round(2.78)
|
||||||
|
3
|
||||||
|
```
|
||||||
|
|
||||||
|
## Пункт 6
|
||||||
|
Убедился, что малые и большие буквы при именовании объектов различаются
|
||||||
|
```
|
||||||
|
Gg1=45
|
||||||
|
gg1;Gg1
|
||||||
|
1.6
|
||||||
|
45
|
||||||
|
```
|
||||||
|
|
||||||
|
## Пункт 7
|
||||||
|
Изучение простые базовые типы объектов
|
||||||
|
|
||||||
|
### Пункт 7.1
|
||||||
|
Логический тип:
|
||||||
|
```
|
||||||
|
bb1=True; bb2=False
|
||||||
|
bb1;bb2
|
||||||
|
True
|
||||||
|
False
|
||||||
|
```
|
||||||
|
Вывел на экран класс объекта:
|
||||||
|
```
|
||||||
|
type(bb1)
|
||||||
|
<class 'bool'>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Пункт 7.2
|
||||||
|
Другие простые типы
|
||||||
|
Вещественный тип
|
||||||
|
```
|
||||||
|
ii1=-1234567890
|
||||||
|
```
|
||||||
|
Экспоненциальная форма записи вещественного числа
|
||||||
|
```
|
||||||
|
ff1=-8.9876e-12
|
||||||
|
```
|
||||||
|
Двоичное число
|
||||||
|
```
|
||||||
|
dv1=0b1101010
|
||||||
|
```
|
||||||
|
Восьмеричное число
|
||||||
|
```
|
||||||
|
vsm1=0o52765
|
||||||
|
```
|
||||||
|
шестнадцатиричное число
|
||||||
|
```
|
||||||
|
shest1=0x7109af6
|
||||||
|
```
|
||||||
|
|
||||||
|
Работа с комплексными числами
|
||||||
|
```
|
||||||
|
cc1=2-3j
|
||||||
|
a=3.67; b=-0.45
|
||||||
|
cc2=complex(a,b)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Пункт 7.3
|
||||||
|
Строка символов
|
||||||
|
|
||||||
|
Создал строку символов, убедился, что строки можно заключать в апотрофы и двойные кавычки
|
||||||
|
```
|
||||||
|
ss1='Это - строка символов'
|
||||||
|
ss1
|
||||||
|
'Это - строка символов'
|
||||||
|
ss1="Это - строка символов"
|
||||||
|
ss1
|
||||||
|
'Это - строка символов'
|
||||||
|
```
|
||||||
|
|
||||||
|
Применил внутри строки экранированные последовательности, создал следующую строку
|
||||||
|
```
|
||||||
|
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
|
||||||
|
print(ss1a)
|
||||||
|
Это - " строка символов ",
|
||||||
|
выводимая на двух строках
|
||||||
|
```
|
||||||
|
Создал ещё одну строку, выводимую на двух строках
|
||||||
|
```
|
||||||
|
ss1b= 'Меня зовут: \n Ходюк М. Р.'
|
||||||
|
print(ss1b)
|
||||||
|
Меня зовут:
|
||||||
|
Ходюк М. Р.
|
||||||
|
```
|
||||||
|
|
||||||
|
Многострочные строки можно задавать в виде значения объекта с использованием тройных кавычек
|
||||||
|
```
|
||||||
|
mnogo="""Нетрудно заметить , что в результате операции
|
||||||
|
над числами разных типов получается число,
|
||||||
|
имеющее более сложный тип из тех, которые участвуют в операции."""
|
||||||
|
print(mnogo)
|
||||||
|
Нетрудно заметить , что в результате операции
|
||||||
|
над числами разных типов получается число,
|
||||||
|
имеющее более сложный тип из тех, которые участвуют в операции.
|
||||||
|
```
|
||||||
|
|
||||||
|
Изучил возможность обращения к частям строки по индексам символов начиная с 0
|
||||||
|
```
|
||||||
|
ss1[0]
|
||||||
|
'Э'
|
||||||
|
ss1[0]
|
||||||
|
'Э'
|
||||||
|
ss1[8]
|
||||||
|
'р'
|
||||||
|
ss1[-2]
|
||||||
|
'о'
|
||||||
|
ss1[6:9]
|
||||||
|
'стр'
|
||||||
|
ss1[13:]
|
||||||
|
'символов'
|
||||||
|
ss1[:13]
|
||||||
|
'Это - строка '
|
||||||
|
ss1[5:-8]
|
||||||
|
' строка '
|
||||||
|
ss1[3:17:2]
|
||||||
|
' тоасм'
|
||||||
|
```
|
||||||
|
|
||||||
|
При задании отрицательного шага, результатом выполнения будет часть строки, в которую символы будут взяты в обратной последовательности
|
||||||
|
```
|
||||||
|
ss1[17:3:-2]
|
||||||
|
'омсаот '
|
||||||
|
```
|
||||||
|
Также можно вместо 17 использовать индекс -4, и получить такой же результат
|
||||||
|
```
|
||||||
|
ss1[-4:3:-2]
|
||||||
|
'омсаот '
|
||||||
|
```
|
||||||
|
Убедился, что строка является неизменяемым объектом
|
||||||
|
```
|
||||||
|
ss1[4]='='
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<pyshell#78>", line 1, in <module>
|
||||||
|
ss1[4]='='
|
||||||
|
TypeError: 'str' object does not support item assignment
|
||||||
|
```
|
||||||
|
Однако строку можно изменить, переопределив её
|
||||||
|
```
|
||||||
|
ss1=ss1[:4]+'='+ss1[5:]
|
||||||
|
ss1
|
||||||
|
'Это = строка символов'
|
||||||
|
```
|
||||||
|
На основе ранее созданной строки ss1b создал обьекты с разными срезами исходной строки
|
||||||
|
```
|
||||||
|
ss1b[:15]
|
||||||
|
'Меня зовут: \n Х'
|
||||||
|
ss1c=ss1b[:3]+'12345'+ss1b[5:]
|
||||||
|
ss1c
|
||||||
|
'Мен12345зовут: \n Ходюк М. Р.'
|
||||||
|
```
|
||||||
|
|
||||||
|
Задал несколько объектов разных типов
|
||||||
|
```
|
||||||
|
Flag = False
|
||||||
|
type(Flag)
|
||||||
|
<class 'bool'>
|
||||||
|
Stroka="СТРОКА"
|
||||||
|
A=453
|
||||||
|
B=4231
|
||||||
|
complex(A,B)
|
||||||
|
(453+4231j)
|
||||||
|
Flag
|
||||||
|
False
|
||||||
|
Stroka
|
||||||
|
'СТРОКА'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Пункт 8
|
||||||
|
Изучение более сложных типов объектов
|
||||||
|
|
||||||
|
### Пункт 8.1
|
||||||
|
Списки
|
||||||
|
|
||||||
|
Создал примеры списков:
|
||||||
|
```
|
||||||
|
spis1=[111,'Spisok',5-9j]
|
||||||
|
spis1
|
||||||
|
[111, 'Spisok', (5-9j)]
|
||||||
|
stup=[0,0,1,1,1,1,1,1,1]
|
||||||
|
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]
|
||||||
|
```
|
||||||
|
|
||||||
|
Изучил возможность изменения списков:
|
||||||
|
```
|
||||||
|
spis1[1]='Список'
|
||||||
|
spis1
|
||||||
|
[111, 'Список', (5-9j)]
|
||||||
|
```
|
||||||
|
Узнал текущее число элементов в списке
|
||||||
|
```
|
||||||
|
len(spis1)
|
||||||
|
3
|
||||||
|
```
|
||||||
|
Изучил возможность добавления элементов в списки с помощью метода append и с помощью конкатенации
|
||||||
|
```
|
||||||
|
spis1.append('New item')
|
||||||
|
spis1+['New item']
|
||||||
|
[111, 'Список', (5-9j), 'New item', 'New item']
|
||||||
|
```
|
||||||
|
В последней инструкции объект только выводится, но не сохраняется
|
||||||
|
```
|
||||||
|
spis1
|
||||||
|
[111, 'Список', (5-9j), 'New item']
|
||||||
|
```
|
||||||
|
Добавил в конец списка spis1 строку ss1b
|
||||||
|
```
|
||||||
|
spis1.append(ss1b)
|
||||||
|
spis1
|
||||||
|
[111, 'Список', (5-9j), 'New item', 'Меня зовут: \n Ходюк М. Р.']
|
||||||
|
```
|
||||||
|
|
||||||
|
Изучил возможность удаления элемента
|
||||||
|
```
|
||||||
|
spis1.pop(1)
|
||||||
|
'Список'
|
||||||
|
spis1
|
||||||
|
[111, (5-9j), 'New item', 'Меня зовут: \n Ходюк М. Р.']
|
||||||
|
```
|
||||||
|
Метод удалил из списка элемент с индексом 1
|
||||||
|
|
||||||
|
Самостоятельно изучил другие методы списков и применил их
|
||||||
|
```
|
||||||
|
help(spis.insert)
|
||||||
|
Help on built-in function insert:
|
||||||
|
|
||||||
|
insert(index, object, /) method of builtins.list instance
|
||||||
|
Insert object before index.
|
||||||
|
|
||||||
|
spis1.insert(3,'home')
|
||||||
|
spis1
|
||||||
|
[111, (5-9j), 'New item', 'home', 'Меня зовут: \n Ходюк М. Р.']
|
||||||
|
|
||||||
|
help(spis.remove)
|
||||||
|
Help on built-in function remove:
|
||||||
|
|
||||||
|
remove(value, /) method of builtins.list instance
|
||||||
|
Remove first occurrence of value.
|
||||||
|
|
||||||
|
Raises ValueError if the value is not present.
|
||||||
|
|
||||||
|
spis23=[1,2,3,1]
|
||||||
|
spis23.remove(1)
|
||||||
|
spis23
|
||||||
|
[2, 3, 1]
|
||||||
|
|
||||||
|
help(spis.extend)
|
||||||
|
Help on built-in function extend:
|
||||||
|
|
||||||
|
extend(iterable, /) method of builtins.list instance
|
||||||
|
Extend list by appending elements from the iterable.
|
||||||
|
|
||||||
|
spis23.extend(spis1)
|
||||||
|
spis23
|
||||||
|
[2, 3, 1, 111, (5-9j), 'New item', 'home', 'Меня зовут: \n Ходюк М. Р.']
|
||||||
|
|
||||||
|
help(spis.clear)
|
||||||
|
Help on built-in function clear:
|
||||||
|
|
||||||
|
clear() method of builtins.list instance
|
||||||
|
Remove all items from list.
|
||||||
|
|
||||||
|
spis24=[1,2,3,4,5]
|
||||||
|
spis24
|
||||||
|
[1, 2, 3, 4, 5]
|
||||||
|
spis24.clear()
|
||||||
|
spis24
|
||||||
|
[]
|
||||||
|
|
||||||
|
spis24=[1,2,8,3,6,4,12,7]
|
||||||
|
spis24.sort()
|
||||||
|
spis24
|
||||||
|
[1, 2, 3, 4, 6, 7, 8, 12]
|
||||||
|
|
||||||
|
spis24.reverse()
|
||||||
|
spis24
|
||||||
|
[12, 8, 7, 6, 4, 3, 2, 1]
|
||||||
|
|
||||||
|
help(spis.copy)
|
||||||
|
Help on built-in function copy:
|
||||||
|
|
||||||
|
copy() method of builtins.list instance
|
||||||
|
Return a shallow copy of the list.
|
||||||
|
|
||||||
|
spis25=spis24.copy()
|
||||||
|
spis25
|
||||||
|
[12, 8, 7, 6, 4, 3, 2, 1]
|
||||||
|
|
||||||
|
help(spis.count)
|
||||||
|
Help on built-in function count:
|
||||||
|
|
||||||
|
count(value, /) method of builtins.list instance
|
||||||
|
Return number of occurrences of value.
|
||||||
|
|
||||||
|
stup
|
||||||
|
[0, 0, 1, 1, 1, 1, 1, 1, 1]
|
||||||
|
stup.count(0)
|
||||||
|
2
|
||||||
|
|
||||||
|
help(spis.index)
|
||||||
|
Help on built-in function index:
|
||||||
|
|
||||||
|
index(value, start=0, stop=9223372036854775807, /) method of builtins.list instance
|
||||||
|
Return first index of value.
|
||||||
|
|
||||||
|
Raises ValueError if the value is not present.
|
||||||
|
|
||||||
|
stup.index(1)
|
||||||
|
2
|
||||||
|
```
|
||||||
|
|
||||||
|
Списки могут быть вложенными
|
||||||
|
```
|
||||||
|
spis2=[spis1,[4,5,6,7]]
|
||||||
|
```
|
||||||
|
Обратился к элементам вложенного списка и изменение их
|
||||||
|
```
|
||||||
|
spis2[0][1]
|
||||||
|
(5-9j)
|
||||||
|
spis2[0][1]=78
|
||||||
|
spis2
|
||||||
|
[[111, 78, 'New item', 'home', 'Меня зовут: \n Ходюк М. Р.'], [4, 5, 6, 7]]
|
||||||
|
```
|
||||||
|
При изменении элементов вложенного списка изменяется и сам список, который был вложен в другой
|
||||||
|
```
|
||||||
|
spis1
|
||||||
|
[111, 78, 'New item', 'home', 'Меня зовут: \n Ходюк М. Р.']
|
||||||
|
```
|
||||||
|
|
||||||
|
Создал свой объект список
|
||||||
|
```
|
||||||
|
spisok=[12, 'Strocka', Flag, spis25]
|
||||||
|
spisok
|
||||||
|
[12, 'Strocka', False, [12, 8, 7, 6, 4, 3, 2, 1]]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Пункт 8.2
|
||||||
|
Объект-кортеж
|
||||||
|
Изучил примеры операций с кортежами:
|
||||||
|
Создание:
|
||||||
|
```
|
||||||
|
kort1=(222,'Kortezh',77+8j)
|
||||||
|
```
|
||||||
|
Переопределение(т.к.кортеж является неизменяемым объектом)
|
||||||
|
```
|
||||||
|
kort1= kort1+(1,2)
|
||||||
|
kort1= kort1+(ss1b,)
|
||||||
|
kort1
|
||||||
|
(222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут: \n Ходюк М. Р.')
|
||||||
|
```
|
||||||
|
|
||||||
|
Переопределил кортеж с удалением комплексного значения
|
||||||
|
```
|
||||||
|
kort2=kort1[:2]+kort1[3:]
|
||||||
|
kort2
|
||||||
|
(222, 'Kortezh', 1, 2, 'Меня зовут: \n Ходюк М. Р.')
|
||||||
|
```
|
||||||
|
Изучил важные методы кортежей
|
||||||
|
Получение индекса заданного элемента(index) и подсчёт числа вхождений заданного элемента(count)
|
||||||
|
```
|
||||||
|
kort1.index(2)
|
||||||
|
4
|
||||||
|
kort1.count(222)
|
||||||
|
1
|
||||||
|
```
|
||||||
|
Попробовал операцию изменения элемента кортежа и убедился в невозможности его изменения
|
||||||
|
```
|
||||||
|
kort1[2]=90
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<pyshell#174>", line 1, in <module>
|
||||||
|
kort1[2]=90
|
||||||
|
TypeError: 'tuple' object does not support item assignment
|
||||||
|
```
|
||||||
|
Самостроятельно создал кортеж:
|
||||||
|
```
|
||||||
|
kortej=(12, 'Strocka', Flag, spis25)
|
||||||
|
kortej
|
||||||
|
(12, 'Strocka', False, [12, 8, 7, 6, 4, 3, 2, 1])
|
||||||
|
```
|
||||||
|
|
||||||
|
### Пункт 8.3
|
||||||
|
Словари
|
||||||
|
Пример создания словаря и обращения к его элементам по ключам
|
||||||
|
```
|
||||||
|
dic1={'Saratov':145, 'Orel':56, 'Vologda':45}
|
||||||
|
dic1['Orel']
|
||||||
|
56
|
||||||
|
```
|
||||||
|
|
||||||
|
Пример пополнения словаря
|
||||||
|
|
||||||
|
```
|
||||||
|
dic1['Pskov']=78
|
||||||
|
dic1
|
||||||
|
{'Saratov': 145, 'Orel': 56, 'Vologda': 45, 'Pskov': 78}
|
||||||
|
```
|
||||||
|
|
||||||
|
Применил методы получения списка ключей и значений в словаре:
|
||||||
|
```
|
||||||
|
dic1.keys()
|
||||||
|
dict_keys(['Saratov', 'Orel', 'Vologda', 'Pskov'])
|
||||||
|
dic1.values()
|
||||||
|
dict_values([145, 56, 45, 78])
|
||||||
|
```
|
||||||
|
|
||||||
|
Применил функцию sorted для получения списков, упорядоченные по ключам/значениям
|
||||||
|
```
|
||||||
|
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'
|
||||||
|
```
|
||||||
|
|
||||||
|
Создал более сложный словарь с использованием функции dict
|
||||||
|
```
|
||||||
|
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 Ходюк М. Р.'}
|
||||||
|
```
|
||||||
|
|
||||||
|
Создал ещё один словарь с использованием функций dict и zip
|
||||||
|
```
|
||||||
|
dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b]))
|
||||||
|
dic5
|
||||||
|
{'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут: \n Ходюк М. Р.'}
|
||||||
|
```
|
||||||
|
|
||||||
|
Создал объект-кортеж с 7 элементами и список с 5 элементами, и попробовал создать из них словарь:
|
||||||
|
```
|
||||||
|
kort801 = (1, 48, 'NICOLAI', '67W', 'Батон', 'name', 1453)
|
||||||
|
spisocek = [1,4553, 'Maxim',4,6]
|
||||||
|
dic6=dict(zip(kort801, spisocek))
|
||||||
|
dic6
|
||||||
|
{1: 1, 48: 4553, 'NICOLAI': 'Maxim', '67W': 4, 'Батон': 6}
|
||||||
|
```
|
||||||
|
Как можно заметить, словарь создался с 5ю элементами, из чего можно сделать вывод, что при неодиноковом количестве задаваемых ключей и значений, словарь создастся с кол-вом
|
||||||
|
элементов, равным меньшему их кол-ву
|
||||||
|
|
||||||
|
Пример словаря с описанием состава студентов, обучающихся на АВТИ:
|
||||||
|
```
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
### Пункт 8.4
|
||||||
|
Множества
|
||||||
|
|
||||||
|
Пример создания множества
|
||||||
|
```
|
||||||
|
mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
|
||||||
|
mnoz1
|
||||||
|
{'двигатель', 'датчик', 'линия связи', 'микропроцессор'}
|
||||||
|
```
|
||||||
|
|
||||||
|
Определение числа элементов в множестве
|
||||||
|
```
|
||||||
|
len(mnoz1)
|
||||||
|
4
|
||||||
|
```
|
||||||
|
проверка наличия элемента во множестве
|
||||||
|
```
|
||||||
|
'датчик' in mnoz1
|
||||||
|
True
|
||||||
|
```
|
||||||
|
Добавление элемента
|
||||||
|
```
|
||||||
|
mnoz1.add('реле')
|
||||||
|
mnoz1
|
||||||
|
{'двигатель', 'датчик', 'линия связи', 'реле', 'микропроцессор'}
|
||||||
|
```
|
||||||
|
Удаление элемента
|
||||||
|
```
|
||||||
|
mnoz1.remove('линия связи')
|
||||||
|
mnoz1
|
||||||
|
{'двигатель', 'датчик', 'реле', 'микропроцессор'}
|
||||||
|
```
|
||||||
|
|
||||||
|
Создал объект-множество с элементами разныхтипов и попробовал выполнить с ним разные операции
|
||||||
|
```
|
||||||
|
mnoz2={7,'Ronaldo',10,'Messi',18,'Bruno'}
|
||||||
|
mnoz2
|
||||||
|
{18, 7, 'Bruno', 10, 'Ronaldo', 'Messi'}
|
||||||
|
len(mnoz2)
|
||||||
|
6
|
||||||
|
mnoz2.add('Pele')
|
||||||
|
mnoz2
|
||||||
|
{18, 'Pele', 7, 'Bruno', 10, 'Ronaldo', 'Messi'}
|
||||||
|
mnoz2.remove('Messi')
|
||||||
|
mnoz2
|
||||||
|
{18, 'Pele', 7, 'Bruno', 10, 'Ronaldo'}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Пункт 9
|
||||||
|
Закончил сеанс работы с IDLE
|
||||||
Загрузка…
Ссылка в новой задаче