форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
811 строки
24 KiB
Markdown
811 строки
24 KiB
Markdown
# Отчёт по теме 2
|
|
Зеленкина Катерина, А-02-23
|
|
|
|
## Пункт 1. Запуск оболочки IDLE
|
|
|
|
Установим рабочий каталог:
|
|
|
|
```py
|
|
>>> import os
|
|
>>> os.chdir(r'C:\Users\user\python-labs\TEMA2')
|
|
```
|
|
## Пункт 2. Простые объекты
|
|
Рассмотрела операции присваивания:
|
|
|
|
```py
|
|
f1=16; f2=3
|
|
f1,f2
|
|
(16, 3)
|
|
f1;f2
|
|
16
|
|
3
|
|
```
|
|
|
|
Просмотрела уже существующие объекты в данный момент в среде Python:
|
|
|
|
```py
|
|
>>> dir()
|
|
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2', 'os']
|
|
```
|
|
|
|
Просмотрела список атрибутов объекта f1:
|
|
|
|
```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']
|
|
```
|
|
|
|
Определила классовую принадлежность объекта f2:
|
|
|
|
```py
|
|
>>> type(f2)
|
|
<class 'int'>
|
|
```
|
|
|
|
Удалила объекты f1 и f2:
|
|
|
|
```py
|
|
>>> del f1,f2
|
|
>>> f1;f2
|
|
Traceback (most recent call last):
|
|
File "<pyshell#9>", line 1, in <module>
|
|
f1;f2
|
|
NameError: name 'f1' is not defined
|
|
```
|
|
|
|
## Пункт 3. Правила именования объектов в Python.
|
|
|
|
Выполнила следующие предложенные операции. Последние две из них имели недопустимые имена:
|
|
|
|
```py
|
|
>>> gg1=1.6
|
|
>>> gg1
|
|
1.6
|
|
>>> hh1='Строка'
|
|
>>> hh1
|
|
'Строка'
|
|
>>> 73sr=3 - неправильное именование
|
|
SyntaxError: invalid decimal literal
|
|
>>> and=7 - неправильное именование
|
|
SyntaxError: invalid syntax
|
|
```
|
|
|
|
## Пункты 4-5. Список ключевых слов и встроенных идентификаторов
|
|
|
|
Вывела список ключевых слов и сохранила его в переменную
|
|
|
|
```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']
|
|
>>> a = keyword.kwlist
|
|
>>> 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', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
|
|
```
|
|
|
|
Вывела список встроенных идентификаторов:
|
|
|
|
```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', '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']
|
|
```
|
|
|
|
### Функция abs()
|
|
|
|
```py
|
|
>>> help (abs)
|
|
Help on built-in function abs in module builtins:
|
|
|
|
abs(x, /)
|
|
Return the absolute value of the argument.
|
|
|
|
>>> abs(-1)
|
|
1
|
|
```
|
|
|
|
### Функция len()
|
|
|
|
```py
|
|
>>> help (len)
|
|
Help on built-in function len in module builtins:
|
|
|
|
len(obj, /)
|
|
Return the number of items in a container.
|
|
|
|
>>> b=[0,1,2,3,4,5,6,7,8,9,10]
|
|
>>> b
|
|
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
|
>>> len(b)
|
|
11
|
|
```
|
|
|
|
### Функции max()/min()
|
|
|
|
```py
|
|
>>> 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.
|
|
|
|
>>> max(b)
|
|
10
|
|
>>> min(b)
|
|
0
|
|
```
|
|
|
|
### Функция pow()
|
|
|
|
```py
|
|
>>> 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.
|
|
|
|
>>> pow(6,2)
|
|
36
|
|
```
|
|
|
|
### Функция round()
|
|
|
|
```py
|
|
>>> 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.
|
|
|
|
>>> round(3.8)
|
|
4
|
|
```
|
|
|
|
### Функция sorted()
|
|
|
|
```py
|
|
>>> 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.
|
|
|
|
>>> c=[10, 4, 9, 1, 23]
|
|
>>> c
|
|
[10, 4, 9, 1, 23]
|
|
>>> sorted(c)
|
|
[1, 4, 9, 10, 23]
|
|
```
|
|
|
|
### Функция sum()
|
|
|
|
```py
|
|
>>> 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.
|
|
|
|
>>> sum(c)
|
|
47
|
|
```
|
|
|
|
### Функция zip()
|
|
|
|
```py
|
|
>>> 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.
|
|
|
|
>>> c
|
|
[10, 4, 9, 1, 23]
|
|
>>> d=[1,2,3,4,5]
|
|
>>> d
|
|
[1, 2, 3, 4, 5]
|
|
>>> h=zip(c,d)
|
|
>>> h
|
|
<zip object at 0x0000021067B5EC80>
|
|
>>> list(h)
|
|
[(10, 1), (4, 2), (9, 3), (1, 4), (23, 5)]
|
|
```
|
|
|
|
## Пункт 6. Регистр букв
|
|
Проверила влияние больших и малых букв в имени переменных
|
|
|
|
```py
|
|
>>> Gg1=45
|
|
>>> gg1
|
|
1.6
|
|
>>> Gg1
|
|
45
|
|
```
|
|
|
|
## Пункт 7. Простые базовые типы объектов
|
|
### 7.1 Логический тип (bool)
|
|
|
|
```py
|
|
>>> bb1=True; bb2=False
|
|
>>> bb1;bb2
|
|
True
|
|
False
|
|
>>> type(bb1)
|
|
<class 'bool'>
|
|
```
|
|
|
|
### 7.2 Другие простые типы
|
|
|
|
```py
|
|
>>> ii1=-1234567890
|
|
>>> type(ii1)
|
|
<class 'int'>
|
|
|
|
>>> ff1=-8.9876e-12
|
|
>>> type(ff1)
|
|
<class 'float'>
|
|
|
|
>>> dv1=0b1101010 #Двоичное число
|
|
>>> type(dv1)
|
|
<class 'int'>
|
|
```
|
|
Двоичное число сохранено в объекте класса int
|
|
|
|
```py
|
|
>>> vsm1=0o52765 #Восьмеричное число
|
|
>>> type(vsm1)
|
|
<class 'int'>
|
|
|
|
>>> shest1=0x7109af6 #Шестнадцатеричное число
|
|
>>> type(shest1)
|
|
<class 'int'>
|
|
|
|
cc1=2-3j
|
|
type(cc1)
|
|
<class 'complex'>
|
|
```
|
|
|
|
Создание комплексного числа:
|
|
|
|
```py
|
|
a=3.67; b=-0.45
|
|
cc2=complex(a,b)
|
|
type(cc2)
|
|
<class 'complex'>
|
|
```
|
|
|
|
### 7.3 Строка символов
|
|
|
|
Строки выделяются апострофами:
|
|
```py
|
|
>>> ss1='Это - строка символов'
|
|
>>> ss1
|
|
'Это - строка символов'
|
|
```
|
|
|
|
Строки выделяются двойными кавычками:
|
|
```py
|
|
>>> ss1="Это - строка символов"
|
|
>>> ss1
|
|
'Это - строка символов'
|
|
```
|
|
|
|
Попробовала экранированные последовательности:
|
|
|
|
```py
|
|
>>> ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
|
|
>>> print(ss1a)
|
|
Это - " строка символов ",
|
|
выводимая на двух строках
|
|
```
|
|
|
|
Создала строку по шаблону:
|
|
|
|
```py
|
|
>>> ss1b= 'Меня зовут: \n Зеленкина К. М.'
|
|
>>> print(ss1b)
|
|
Меня зовут:
|
|
Зеленкина К. М.
|
|
```
|
|
Многострочные строки:
|
|
|
|
```py
|
|
>>> mnogo="""Нетрудно заметить , что в результате операции
|
|
над числами разных типов получается число,
|
|
имеющее более сложный тип из тех, которые участвуют в операции."""
|
|
|
|
>>> print(mnogo)
|
|
Нетрудно заметить , что в результате операции
|
|
над числами разных типов получается число,
|
|
имеющее более сложный тип из тех, которые участвуют в операции.
|
|
```
|
|
|
|
Обратилась к частям строки с помощью индексов:
|
|
|
|
```py
|
|
>>> ss1[0]
|
|
'Э'
|
|
>>> ss1[8]
|
|
'р'
|
|
>>> ss1[-2]
|
|
'о'
|
|
```
|
|
|
|
Выполнила операцию «разрезания»/«создания среза»:
|
|
```py
|
|
>>> ss1[6:9]
|
|
'стр'
|
|
>>> ss1[13:]
|
|
'символов'
|
|
>>> ss1[:13]
|
|
'Это - строка '
|
|
>>> ss1[5:-8]
|
|
' строка '
|
|
>>> ss1[3:17:2]
|
|
' тоасм'
|
|
```
|
|
|
|
При отрицательном значении шага перечислились элементы с индексами от 3 до 17 в обратном порядке:
|
|
```py
|
|
>>> ss1[17:3:-2]
|
|
'омсаот '
|
|
```
|
|
|
|
Заменив 17 на -4, мы получим тот-же результат, т. к. символ под индексом 17 и -4 один и тот же:
|
|
|
|
```py
|
|
>>> ss1[-4:3:-2]
|
|
'омсаот '
|
|
```
|
|
|
|
Строка является неизменяемым объектом, поэтому нам выдаст ошибку при попытке внести изменения:
|
|
|
|
```py
|
|
ss1[4]='='
|
|
Traceback (most recent call last):
|
|
File "<pyshell#11>", line 1, in <module>
|
|
ss1[4]='='
|
|
TypeError: 'str' object does not support item assignment
|
|
```
|
|
|
|
```py
|
|
>>> sk1=ss1b[:4]+' именовать'+ss1b[12:]; print(sk1)
|
|
Меня именовать
|
|
Зеленкина К. М.
|
|
```
|
|
Самостоятельно придумала значения и создала объекты разных типов:
|
|
|
|
```py
|
|
>>> flag = True
|
|
>>> type(flag)
|
|
<class 'bool'>
|
|
|
|
>>> n=16
|
|
>>> type(n)
|
|
<class 'int'>
|
|
|
|
>>> k = 'Привет'
|
|
>>> type(k)
|
|
<class 'str'>
|
|
```
|
|
|
|
## Пункт 8. Сложные типы объектов
|
|
### 8.1 Списки
|
|
|
|
__Список__ — это упорядоченная коллекция элементов произвольных типов (числа, строки, другие объекты).
|
|
|
|
Список с элементами разных типов:
|
|
|
|
```py
|
|
>>> spis1=[111, 'Spisok' ,5-9j]
|
|
>>> spis1
|
|
[111, 'Spisok', (5-9j)]
|
|
```
|
|
|
|
Вводить элементы в списках можно на разных строках до закрытия квадратной скобкой:
|
|
|
|
```py
|
|
>>> 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]
|
|
```
|
|
|
|
В списках тоже можно обращаться к элементам по индексам:
|
|
|
|
```py
|
|
>>> spis1[-1]
|
|
(5-9j)
|
|
|
|
>>> stup[-8::2]
|
|
[0, 1, 1, 1]
|
|
```
|
|
|
|
Пояснение: Вошло 4 элемента. Элемент под индексом '-8' есть элемент с индексом 1, срез произойдёт до последнего элемента с шагом 2
|
|
|
|
Заменила второй элемент в spis1:
|
|
|
|
```py
|
|
>>> spis1[1]='Список'
|
|
>>> spis1
|
|
[111, 'Список', (5-9j)]
|
|
>>> len(spis1)
|
|
3
|
|
```
|
|
|
|
Добавление элементов в список:
|
|
|
|
|
|
```py
|
|
>>> help(spis1.append)
|
|
Help on built-in function append:
|
|
|
|
append(object, /) method of builtins.list instance
|
|
Append object to the end of the list.
|
|
|
|
>>> spis1.append('New item')
|
|
spis1
|
|
[111, 'Список', (5-9j), 'New item']
|
|
|
|
|
|
>>> spis1.append(ss1b)
|
|
>>> spis1
|
|
[111, 'Список', (5-9j), 'New item', 'Меня зовут: \n Зеленкина К. М.']
|
|
>>> spis1.pop(1)
|
|
'Список'
|
|
>>> spis1
|
|
[111, (5-9j), 'New item', 'Меня зовут: \n Зеленкина К. М.']
|
|
```
|
|
|
|
### Другие методы:
|
|
__insert__ - вставляет элемент в нужную позицию
|
|
|
|
```py
|
|
>>> spis1.insert(0, 24); spis1
|
|
[24, 111, (5-9j), 'New item', 'Меня зовут: \n Зеленкина К. М.']
|
|
```
|
|
__remove__ - удалит элемент, указанный в скобках
|
|
|
|
```py
|
|
>>> spis1.remove(24); spis1
|
|
[111, (5-9j), 'New item', 'Меня зовут: \n Зеленкина К. М.']
|
|
```
|
|
|
|
__extend__ - добавляет каждый элемент аргумента
|
|
|
|
```py
|
|
>>> spis1.extend('24'); spis1
|
|
[111, (5-9j), 'New item', 'Меня зовут: \n Зеленкина К. М.', '2', '4']
|
|
```
|
|
|
|
__clear__ - удаляет всё из списка
|
|
|
|
```py
|
|
>>> spis1.clear(); spis1
|
|
[]
|
|
```
|
|
|
|
__sort__ - сортирует элементы в списке по возрастанию, а буквы по алфавиту
|
|
|
|
```py
|
|
>>> spis1=[20, 4, 63, 2, 1, 0, 13, 7]; spis1
|
|
[20, 4, 63, 2, 1, 0, 13, 7]
|
|
>>> spis1.sort()
|
|
>>> spis1
|
|
[0, 1, 2, 4, 7, 13, 20, 63]
|
|
|
|
>>> spis2 = ['д', 'с','г','а','ш']
|
|
>>> spis2.sort()
|
|
>>> spis2
|
|
['а', 'г', 'д', 'с', 'ш']
|
|
```
|
|
|
|
__reverse__ - сортирует элементы в обратном порядке
|
|
|
|
```py
|
|
>>> spis1.reverse(); spis1
|
|
[63, 20, 13, 7, 4, 2, 1, 0]
|
|
|
|
>>> spis2.reverse();spis2
|
|
['ш', 'с', 'д', 'г', 'а']
|
|
```
|
|
|
|
__copy__ - копирует список
|
|
|
|
```py
|
|
>>> vv=spis1.copy(); vv
|
|
[63, 20, 13, 7, 4, 2, 1, 0]
|
|
```
|
|
|
|
__count__ - cчитает количество заданного аргумента в скобках в списке
|
|
|
|
```py
|
|
>>> spis2.count('д')
|
|
1
|
|
```
|
|
|
|
__index__ - выдаёт индекс элемента
|
|
|
|
```py
|
|
>>> spis1.index(20)
|
|
1
|
|
```
|
|
|
|
#### Вложенные списки
|
|
|
|
```py
|
|
>>> spis2=[spis1,[4,5,6,7]]; spis2
|
|
[[63, 20, 13, 7, 4, 2, 1, 0], [4, 5, 6, 7]]
|
|
>>> spis2[0][1] #обращение к элементу списка spis1
|
|
20
|
|
>>> spis2[0][1]=78; spis2 #Замена значения элемента на 78
|
|
[[63, 78, 13, 7, 4, 2, 1, 0], [4, 5, 6, 7]]
|
|
|
|
>>> spis1
|
|
[63, 78, 13, 7, 4, 2, 1, 0]
|
|
```
|
|
|
|
Пояснение: Список spis1 отличается от первоначального, потому что он лежит в другом списке, в котором мы и поменяли значение
|
|
|
|
Создала список с разными типами данных
|
|
|
|
```py
|
|
>>>spisok = [89, 'дом', True, ['яблоко', 'помидор', 'хлеб']]; spisok
|
|
|
|
[89, 'дом', True, ['яблоко', 'помидор', 'хлеб']]
|
|
>>> type(spisok)
|
|
|
|
<class 'list'>
|
|
```
|
|
|
|
### 8.2 Кортежи
|
|
|
|
__Кортеж__ – кортежи являются последовательностями, как списки, но они являются неизменяемыми, как строки.
|
|
|
|
```py
|
|
>>> kort1=(222,'Kortezh',77+8j); kort1
|
|
|
|
(222, 'Kortezh', (77+8j))
|
|
```
|
|
|
|
Переопределим кортеж:
|
|
|
|
1. Добавим элементы
|
|
|
|
```py
|
|
>>> kort1= kort1+(1,2)
|
|
>>> kort1
|
|
(222, 'Kortezh', (77+8j), 1, 2)
|
|
|
|
>>> kort1= kort1+(ss1b,); kort1
|
|
(222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут: \n Зеленкина К. М.')
|
|
```
|
|
|
|
2. Удалим элементы:
|
|
|
|
```py
|
|
>>> kort2=kort1[:2]+kort1[3:]; kort2
|
|
(222, 'Kortezh', 1, 2, 'Меня зовут: \n Зеленкина К. М.')
|
|
```
|
|
|
|
Узнала индекс заданного элемента:
|
|
|
|
```py
|
|
>>> kort1.index(2)
|
|
4
|
|
```
|
|
|
|
Подсчитала количество вхождений заданного элемента в кортеже:
|
|
|
|
```py
|
|
>>> kort1.count(222)
|
|
1
|
|
```
|
|
|
|
Т. к. кортежи неизменяемы, то у них отсутствуют методы append и pop.
|
|
Попробуем заменить элемент в кортеже (выдаст ошибку):
|
|
|
|
```py
|
|
>>> kort1[2]=90
|
|
Traceback (most recent call last):
|
|
File "<pyshell#161>", line 1, in <module>
|
|
kort1[2]=90
|
|
TypeError: 'tuple' object does not support item assignment
|
|
```
|
|
|
|
### Создаю объект-кортеж с разными типами данных:
|
|
|
|
```py
|
|
>>> kort2=(23, 'Тыква', [4, 5, 6, 7], (4, 6, 8, 10))
|
|
kort2
|
|
(23, 'Тыква', [4, 5, 6, 7], (4, 6, 8, 10))
|
|
type(kort2)
|
|
|
|
<class 'tuple'>
|
|
```
|
|
|
|
## 8.3 Словарь
|
|
__Словарь__ - совокупность пар: «ключ (key)»:«значение (value)».
|
|
|
|
Создадим словарь:
|
|
|
|
```py
|
|
>>> dic1={'Saratov':145, 'Orel':56, 'Vologda':45}; dic1
|
|
{'Saratov': 145, 'Orel': 56, 'Vologda': 45}
|
|
```
|
|
В словарях обращение к элементам происходит по ключам:
|
|
|
|
```py
|
|
>>> dic1['Orel']
|
|
56
|
|
```
|
|
Изменение словаря, добавление элемента:
|
|
|
|
```py
|
|
>>> dic1['Pskov']=78
|
|
>>> dic1
|
|
{'Saratov': 120, 'Vologda': 45, 'Pskov': 78, 'Orel': 56}
|
|
```
|
|
Отобразим сортированный словарь с помощью функции sorted (Отображает, но не сортирует):
|
|
|
|
```py
|
|
>>> sorted(dic1.keys())
|
|
['Orel', 'Saratov', 'Vologda']
|
|
>>> sorted(dic1.values())
|
|
[45, 56, 145]
|
|
```
|
|
|
|
Элементы словаря могут быть любого типа, даже словарём:
|
|
|
|
```py
|
|
>>> dic2={1:'mean',2:'standart deviation',3:'correlation'}
|
|
>>> dic3={'statistics':dic2,'POAS':['base','elementary','programming']}
|
|
>>> dic3
|
|
{'statistics': {1: 'mean', 2: 'standart deviation', 3: 'correlation'}, 'POAS': ['base', 'elementary', 'programming']}
|
|
|
|
>>> dic3['statistics'][2]
|
|
'standart deviation'
|
|
```
|
|
|
|
Создадим более сложный словарь:
|
|
|
|
```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 Зеленкина К. М.'}
|
|
|
|
>>> dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b])); dic5
|
|
{'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут: \n Зеленкина К. М.'}
|
|
```
|
|
|
|
Создадим свой объект-кортеж и объект-список:
|
|
|
|
```py
|
|
>>> spisok01=(1, 5, 7, 9, 3, 0,10); spisok01
|
|
(1, 5, 7, 9, 3, 0, 10)
|
|
>>> spisok02=[22,10,7,45,100]; spisok02
|
|
[22, 10, 7, 45, 100]
|
|
>>>spisok03=dict(zip(spisok01,spisok02)); spisok03
|
|
{1: 22, 5: 10, 7: 7, 9: 45, 3: 100}
|
|
|
|
>>> len(spisok03)
|
|
5 #Элементов 5, потому что в spisok02 всего пять элементов
|
|
```
|
|
|
|
Пример словаря с описанием состава студентов, обучающихся на АВТИ:
|
|
|
|
```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
|
|
```
|
|
|
|
## 8.4 Множество
|
|
|
|
__Объект-множество__ – это неупорядоченная совокупность неповторяющихся элементов.
|
|
|
|
```py
|
|
>>> mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}; mnoz1
|
|
{'линия связи', 'микропроцессор', 'двигатель', 'датчик'}
|
|
|
|
>>> len(mnoz1)
|
|
4
|
|
|
|
>>> 'датчик' in mnoz1
|
|
True
|
|
|
|
>>> mnoz1.add('реле')
|
|
>>> mnoz1
|
|
{'линия связи', 'датчик', 'двигатель', 'реле', 'микропроцессор'}
|
|
|
|
>>> mnoz1.remove('линия связи'); mnoz1
|
|
{'датчик', 'двигатель', 'реле', 'микропроцессор'}
|
|
```
|
|
|
|
Создадим своё множество:
|
|
|
|
```py
|
|
>>> mnoz2={5, 'яблоко', False, (10, 6, 0)}; mnoz2
|
|
{False, 5, (10, 6, 0), 'яблоко'}
|
|
|
|
>>> mnoz2.add(100); mnoz2
|
|
{False, 100, 5, (10, 6, 0), 'яблоко'}
|
|
|
|
>>> mnoz2.remove('яблоко'); mnoz2
|
|
{False, 100, 5, (10, 6, 0)}
|
|
|
|
>>>False in mnoz2
|
|
True
|
|
```
|
|
|
|
## 9. Конец сеанса
|
|
|