Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1128 строки
35 KiB
Python

Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
import os
os.chdir('D:\\Уник\\5 семестр\\Программное обеспечение автоматизированных систем\\python-labs\\TEMA2'\\)
SyntaxError: unexpected character after line continuation character
os.chdir('D:\\Уник\\5 семестр\\Программное обеспечение автоматизированных систем\\python-labs\\TEMA2\\')
os.getcwd
<built-in function getcwd>
os.getcwd()
'D:\\Уник\\5 семестр\\Программное обеспечение автоматизированных систем\\python-labs\\TEMA2'
f1=16; f2=3
f1,f2
(16, 3)
f1;f2
16
3
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2', 'os']
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'>
del f1,f2
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os']
gg1=1.6 #значение в виде вещественного числа
hh1='Строка' #значение в виде символьной строки
73sr=3 #неправильное имя – начинается с цифры - будет диагностика!
SyntaxError: invalid decimal literal
and=7 #недопустимое имя – совпадает с ключевым словом - будет диагностика!
SyntaxError: unexpected indent
and=7 #недопустимое имя – совпадает с ключевым словом - будет диагностика!
SyntaxError: invalid syntax
SyntaxError: invalid syntax
SyntaxError: invalid syntax
import keyword
SyntaxError: unexpected indent
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']
keywords = 'keyword.kwlist'
keywords
'keyword.kwlist'
keywords = keyword.kwlist
keywords
['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']
clear
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
clear
NameError: name 'clear' is not defined
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.
Ggl=45
Ggl;ggl
45
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
Ggl;ggl
NameError: name 'ggl' is not defined. Did you mean: 'Ggl'?
bb1=True; bb2=False
bb1;bb2
True
False
type(bb1) #функция, показывающая тип (класс) объекта
<class 'bool'>
ii1=-1234567890
ff1=-8.9876e-12 #экспоненциальная форма записи вещественного числа
dv1=0b1101010 #Это – двоичное число. В объекте какого класса оно сохранено?
type(dvl)
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
type(dvl)
NameError: name 'dvl' is not defined. Did you mean: 'dv1'?
type(dv1)
<class 'int'>
vsm1=0o52765 #Это – восьмеричное число
shest1=0x7109af6 #Это – шестнадцатеричное число
cc1=2-3j
a=3.67; b=-0.45
cc2=complex(a,b) #Создается комплексное число
cc2
(3.67-0.45j)
ss1='Это - строка символов'
ss1
'Это - строка символов'
ss1="Это - строка символов"
ss1
'Это - строка символов'
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
ss1a
'Это - " строка символов ", \n \t выводимая на двух строках'
print(ss1a)
Это - " строка символов ",
выводимая на двух строках
ss1b= 'Меня зовут: \n <Румянцев В. А.>'
print(ss1b)
Меня зовут:
<Румянцев В. А.>
mnogo="""Нетрудно заметить , что в результате операции
над числами разных типов получается число,
имеющее более сложный тип из тех, которые участвуют в операции."""
print(mnogo)
Нетрудно заметить , что в результате операции
над числами разных типов получается число,
имеющее более сложный тип из тех, которые участвуют в операции.
ss1[0] #Это – символ «Э»
'Э'
ss1[8] #А это – символ «р»
'р'
ss1[-2] #А это – символ «о» (при знаке «-»(минус) отсчет от конца строки)
'о'
ss1[6:9] #Это часть строки – символы с 6-го индекса по 8-й (9-й не включается!)
'стр'
ss1[13:] #Это часть строки – с 13-го индекса и до конца
'символов'
ss1[:13] #Это часть строки – с начала и до 12-го индекса включительно
'Это - строка '
ss1[5:-8] #Это часть строки – с 5-го индекса и до 8-го от конца
' строка '
ss1[3:17:2] #Часть строки – с 3-го по 16-й индексы с шагом 2
' тоасм'
ss1[17:3:-2]
'омсаот '
ss1[-4:3:-2]
'омсаот '
ss1[4]='=' # Будет диагностика!
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
ss1[4]='=' # Будет диагностика!
TypeError: 'str' object does not support item assignment
ss1=ss1[:4]+'='+ss1[5:]
ssi
Traceback (most recent call last):
File "<pyshell#86>", line 1, in <module>
ssi
NameError: name 'ssi' is not defined. Did you mean: 'ss1'?
ss1
'Это = строка символов'
ss1b[0]
'М'
ss1b[0:20:4]
'М у\nу'
ss1b=ss1b[:10]+':'+'\n <'+ss1b[11:-1]+'>'
ss1b[0:16:4]
'М у '
# 1. Целое число (int)
integer_obj = 42
# 2. Вещественное число (float)
float_obj = 3.14
# 3. Строка (str)
string_obj = "Hello, World!"
# 4. Логический тип (bool)
bool_obj = True
help(list)
Help on class list in module builtins:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, index, /)
| Return self[index].
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the list.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(self, /)
| Return the size of the list in memory, in bytes.
|
| append(self, object, /)
| Append object to the end of the list.
|
| clear(self, /)
| Remove all items from list.
|
| copy(self, /)
| Return a shallow copy of the list.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| insert(self, index, object, /)
| Insert object before index.
|
| pop(self, index=-1, /)
| Remove and return item at index (default last).
|
| Raises IndexError if list is empty or index is out of range.
|
| remove(self, value, /)
| Remove first occurrence of value.
|
| Raises ValueError if the value is not present.
|
| reverse(self, /)
| Reverse *IN PLACE*.
|
| sort(self, /, *, key=None, reverse=False)
| Sort the list in ascending order and return None.
|
| The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
| order of two equal elements is maintained).
|
| If a key function is given, apply it once to each list item and sort them,
| ascending or descending, according to their function values.
|
| The reverse flag can be set to sort in descending order.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(object, /)
| See PEP 585
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
help(tuple)
Help on class tuple in module builtins:
class tuple(object)
| tuple(iterable=(), /)
|
| Built-in immutable sequence.
|
| If no argument is given, the constructor returns an empty tuple.
| If iterable is specified the tuple is initialized from iterable's items.
|
| If the argument is a tuple, the return value is the same object.
|
| Built-in subclasses:
| asyncgen_hooks
| UnraisableHookArgs
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(object, /)
| See PEP 585
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
help(dict)
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(self, /)
| Return the size of the dict in memory, in bytes.
|
| clear(self, /)
| Remove all items from the dict.
|
| copy(self, /)
| Return a shallow copy of the dict.
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(self, /)
| Return a set-like object providing a view on the dict's items.
|
| keys(self, /)
| Return a set-like object providing a view on the dict's keys.
|
| pop(self, key, default=<unrepresentable>, /)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(self, /)
| Return an object providing a view on the dict's values.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(object, /)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
help(set)
Help on class set in module builtins:
class set(object)
| set(iterable=(), /)
|
| Build an unordered collection of unique elements.
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __contains__(self, object, /)
| x.__contains__(y) <==> y in x.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __gt__(self, value, /)
| Return self>value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __reduce__(self, /)
| Return state information for pickling.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| S.__sizeof__() -> size of S in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __xor__(self, value, /)
| Return self^value.
|
| add(self, object, /)
| Add an element to a set.
|
| This has no effect if the element is already present.
|
| clear(self, /)
| Remove all elements from this set.
|
| copy(self, /)
| Return a shallow copy of a set.
|
| difference(self, /, *others)
| Return a new set with elements in the set that are not in the others.
|
| difference_update(self, /, *others)
| Update the set, removing elements found in others.
|
| discard(self, object, /)
| Remove an element from a set if it is a member.
|
| Unlike set.remove(), the discard() method does not raise
| an exception when an element is missing from the set.
|
| intersection(self, /, *others)
| Return a new set with elements common to the set and all others.
|
| intersection_update(self, /, *others)
| Update the set, keeping only elements found in it and all others.
|
| isdisjoint(self, other, /)
| Return True if two sets have a null intersection.
|
| issubset(self, other, /)
| Report whether another set contains this set.
|
| issuperset(self, other, /)
| Report whether this set contains another set.
|
| pop(self, /)
| Remove and return an arbitrary set element.
|
| Raises KeyError if the set is empty.
|
| remove(self, object, /)
| Remove an element from a set; it must be a member.
|
| If the element is not a member, raise a KeyError.
|
| symmetric_difference(self, other, /)
| Return a new set with elements in either the set or other but not both.
|
| symmetric_difference_update(self, other, /)
| Update the set, keeping only elements found in either set, but not in both.
|
| union(self, /, *others)
| Return a new set with elements from the set and all others.
|
| update(self, /, *others)
| Update the set, adding elements from all others.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(object, /)
| See PEP 585
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
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
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+['New item']
[111, 'Список', (5-9j), 'New item', 'New item']
spis1.pop(1)
'Список'
spis1
[111, (5-9j), 'New item']
spis1.append(ssib)
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
spis1.append(ssib)
NameError: name 'ssib' is not defined. Did you mean: 'ss1b'?
spis1.append(ss1b)
spis1
[111, (5-9j), 'New item', 'Меня зовут:\n < \n <Румянцев В. А.>']
help(insert
)
Traceback (most recent call last):
File "<pyshell#126>", line 1, in <module>
help(insert
NameError: name 'insert' is not defined
help(insert)
Traceback (most recent call last):
File "<pyshell#127>", line 1, in <module>
help(insert)
NameError: name 'insert' is not defined
help(spis1.insert)
Help on built-in function insert:
insert(index, object, /) method of builtins.list instance
Insert object before index.
help(spis1.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.
help(spis1.extend)
Help on built-in function extend:
extend(iterable, /) method of builtins.list instance
Extend list by appending elements from the iterable.
help(spis1.clear)
Help on built-in function clear:
clear() method of builtins.list instance
Remove all items from list.
help(spis1.sort)
Help on built-in function sort:
sort(*, key=None, reverse=False) method of builtins.list instance
Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them,
ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
help(spis1.sort)
Help on built-in function sort:
sort(*, key=None, reverse=False) method of builtins.list instance
Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them,
ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
help(spis1.reverse)
Help on built-in function reverse:
reverse() method of builtins.list instance
Reverse *IN PLACE*.
help(spis1.copy)
Help on built-in function copy:
copy() method of builtins.list instance
Return a shallow copy of the list.
help(spis1.count)
Help on built-in function count:
count(value, /) method of builtins.list instance
Return number of occurrences of value.
help(spis1.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.
spis2=[spis1,[4,5,6,7]]
spis2
[[111, (5-9j), 'New item', 'Меня зовут:\n < \n <Румянцев В. А.>'], [4, 5, 6, 7]]
spis2[0][1]
(5-9j)
spis2[0][1]=78
spis2
[[111, 78, 'New item', 'Меня зовут:\n < \n <Румянцев В. А.>'], [4, 5, 6, 7]]
spis1
[111, 78, 'New item', 'Меня зовут:\n < \n <Румянцев В. А.>']
# Элементы списка spis1 отличаются от изначально заданных т.к. список spis2 состоит из списка spis1 и списка [4, 5, 6, 7].
# При изменении списка spis2, а именно списка spis1, меняется изначальное значение элемента списка spis2 - spis1.
myspis=[52, 'shjdfbshjidf', True, spis1]
myspis
[52, 'shjdfbshjidf', True, [111, 78, 'New item', 'Меня зовут:\n < \n <Румянцев В. А.>']]
kort1=(222,'Kortezh',77+8j)
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 < \n <Румянцев В. А.>')
kort1.index(2) # Будет получено значение 3
4
#Получено 4 т.к. ss1b был изменен
kort1.count(222) #Будет получено значение 1
1
kort1[2]=90
Traceback (most recent call last):
File "<pyshell#159>", line 1, in <module>
kort1[2]=90
TypeError: 'tuple' object does not support item assignment
mykort=(222, 'rtgeh', myspis, kort1)
mykort
(222, 'rtgeh', [52, 'shjdfbshjidf', True, [111, 78, 'New item', 'Меня зовут:\n < \n <Румянцев В. А.>']], (222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут:\n < \n <Румянцев В. А.>'))
dic1={'Saratov':145, 'Orel':56, 'Vologda':45}
dic1
{'Saratov': 145, 'Orel': 56, 'Vologda': 45}
dic1['Orel']
56
dic1['Pskov']=78
dic1
{'Saratov': 145, 'Orel': 56, 'Vologda': 45, 'Pskov': 78}
sorted(dic1.keys())
['Orel', 'Pskov', 'Saratov', 'Vologda']
sorted(dic1.values())
[45, 56, 78, 145]
dic2={1:'mean',2:'standart deviation',3:'correlation'}
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'
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 < \n <Румянцев В. А.>'}
dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b]))
dic5
{'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут:\n < \n <Румянцев В. А.>'}
my_tuple = ("яблоко", "банан", "апельсин", "виноград", "киви", "манго", "груша")
my_list = [10, 20, 30, 40, 50]
print("Кортеж (7 элементов):", my_tuple)
Кортеж (7 элементов): ('яблоко', 'банан', 'апельсин', 'виноград', 'киви', 'манго', 'груша')
print("Список (5 элементов):", my_list)
Список (5 элементов): [10, 20, 30, 40, 50]
result_dict = dict(zip(my_tuple, my_list))
result_dict
{'яблоко': 10, 'банан': 20, 'апельсин': 30, 'виноград': 40, 'киви': 50}
# Функция Zip объединяет илементы из нескольких последовательностей.
# Когда самая короткая последовательность заканчивается, функция прекращает свою работу
mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
...
>>> mnoz1
...
{'двигатель', 'микропроцессор', 'датчик', 'линия связи'}
>>> len(mnoz1)
...
4
>>> 'датчик' in mnoz1
...
True
>>> mnoz1.add('реле')
...
>>> mnoz1
...
{'двигатель', 'датчик', 'микропроцессор', 'линия связи', 'реле'}
>>> mnoz1.remove('линия связи')
...
>>> mnoz1
...
{'двигатель', 'датчик', 'микропроцессор', 'реле'}
>>> mymnoz = { 1, 'computer', my_tuple)
...
SyntaxError: closing parenthesis ')' does not match opening parenthesis '{'
>>> mymnoz = { 1, 'computer', my_tuple}
...
>>> mymnoz
...
{('яблоко', 'банан', 'апельсин', 'виноград', 'киви', 'манго', 'груша'), 1, 'computer'}
>>> mymnoz.add('system')
...
>>> mymnoz
...
{('яблоко', 'банан', 'апельсин', 'виноград', 'киви', 'манго', 'груша'), 1, 'system', 'computer'}
>>> mymnoz.remove(my_tuple)
...
>>> mymnoz
...
{1, 'system', 'computer'}