форкнуто от main/python-labs
				
			
			Вы не можете выбрать более 25 тем
			Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
		
		
		
		
		
			
		
			
				
	
	
		
			455 строки
		
	
	
		
			18 KiB
		
	
	
	
		
			Python
		
	
			
		
		
	
	
			455 строки
		
	
	
		
			18 KiB
		
	
	
	
		
			Python
		
	
| #Протокол по Теме 2 Кузьменко Е.А.
 | |
| 
 | |
| #1
 | |
| >>> import os
 | |
| >>> os.chdir(r"C:\Users\Admin\Desktop\python-labs\TEMA2")
 | |
| >>> os.getcwd()
 | |
| 'C:\\Users\\Admin\\Desktop\\python-labs\\TEMA2'
 | |
| 
 | |
| #2
 | |
| >>> 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__', '__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_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
 | |
| >>> type(f1)
 | |
| <class 'int'>
 | |
| >>> del f1
 | |
| >>> del f2
 | |
| >>> dir(f1)
 | |
| Traceback (most recent call last):
 | |
|   File "<pyshell#12>", line 1, in <module>
 | |
|     dir(f1)
 | |
| NameError: name 'f1' is not defined
 | |
| >>> dir()
 | |
| ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os']
 | |
| 
 | |
| #3
 | |
| >>> gg1=1.6; gg1
 | |
| 1.6
 | |
| >>> hh1='Строка'; hh1
 | |
| 'Строка'
 | |
| >>> 73sr=3; 73sr
 | |
| SyntaxError: invalid syntax
 | |
| >>> and=7; and
 | |
| SyntaxError: invalid syntax
 | |
| 
 | |
| #4
 | |
| >>> import keyword
 | |
| >>> keyword.kwlist
 | |
| ['False', 'None', 'True', '__peg_parser__', '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=keyword.kwlist
 | |
| >>> key
 | |
| ['False', 'None', 'True', '__peg_parser__', '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']
 | |
| >>> type(key)
 | |
| <class 'list'>
 | |
| 
 | |
| #5
 | |
| >>> import builtins
 | |
| >>> dir(builtins)
 | |
| ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', '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', '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', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', '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.
 | |
| 
 | |
| >>> abs(13-40)
 | |
| 27
 | |
| >>> help(len)
 | |
| Help on built-in function len in module builtins:
 | |
| 
 | |
| len(obj, /)
 | |
|     Return the number of items in a container.
 | |
| 
 | |
| >>> len("2932")
 | |
| 4
 | |
| >>> len(key)
 | |
| 36
 | |
| >>> 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 arguments, return the largest argument.
 | |
| 
 | |
| >>> max(0,19,20,-2,200,-1012,99,134)
 | |
| 200
 | |
| >>> max("в", "з", "щ", "я")
 | |
| 'я'
 | |
| >>> 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 arguments, return the smallest argument.
 | |
| 
 | |
| >>> min(0,19,20,-2,200,-1012,99,134)
 | |
| -1012
 | |
| >>> min("в", "з", "щ", "я")
 | |
| 'в'
 | |
| >>> 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(2,3)
 | |
| 8
 | |
| >>> pow(2,3,3)
 | |
| 2
 | |
| >>> pow(4,-3)
 | |
| 0.015625
 | |
| >>> 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(123.456)
 | |
| 123
 | |
| >>> round(123.456,1)
 | |
| 123.5
 | |
| >>> round(123.456,-1)
 | |
| 120.0
 | |
| >>> 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.
 | |
| 
 | |
| >>> n=[-10,8,2,-3,5.5]
 | |
| >>> sorted(n)
 | |
| [-10, -3, 2, 5.5, 8]
 | |
| >>> sorted(n,reverse=True)
 | |
| [8, 5.5, 2, -3, -10]
 | |
| >>> w=["apple","banana","kiwi","strawberry"]
 | |
| >>> sorted(w)
 | |
| ['apple', 'banana', 'kiwi', 'strawberry']
 | |
| >>> sorted(w,reverse=True)
 | |
| ['strawberry', 'kiwi', 'banana', 'apple']
 | |
| >>> help(zip)
 | |
| Help on class zip in module builtins:
 | |
| 
 | |
| class zip(object)
 | |
|  |  zip(*iterables) --> A zip object yielding tuples until an input is exhausted.
 | |
|  |  
 | |
|  |     >>> list(zip('abcdefg', range(3), range(4)))
 | |
|  |     [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
 | |
|  |  
 | |
|  |  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.
 | |
|  |  
 | |
|  |  Methods defined here:
 | |
|  |  
 | |
|  |  __getattribute__(self, name, /)
 | |
|  |      Return getattr(self, name).
 | |
|  |  
 | |
|  |  __iter__(self, /)
 | |
|  |      Implement iter(self).
 | |
|  |  
 | |
|  |  __next__(self, /)
 | |
|  |      Implement next(self).
 | |
|  |  
 | |
|  |  __reduce__(...)
 | |
|  |      Return state information for pickling.
 | |
|  |  
 | |
|  |  ----------------------------------------------------------------------
 | |
|  |  Static methods defined here:
 | |
|  |  
 | |
|  |  __new__(*args, **kwargs) from builtins.type
 | |
|  |      Create and return a new object.  See help(type) for accurate signature.
 | |
| 
 | |
| >>> list1=[1,2,3];list2=['a','b','c']
 | |
| >>> z=zip(list1,list2)
 | |
| >>> list(z)
 | |
| [(1, 'a'), (2, 'b'), (3, 'c')]
 | |
| >>> list3=[4,5,6]
 | |
| >>> list(zip(list1,list2,list3))
 | |
| [(1, 'a', 4), (2, 'b', 5), (3, 'c', 6)]
 | |
| 
 | |
| #6
 | |
| >>> Gg1=45
 | |
| >>> gg1
 | |
| 1.6
 | |
| 
 | |
| #7
 | |
| #7.1
 | |
| >>> bb1=True; bb2=False
 | |
| >>> bb1;bb2
 | |
| True
 | |
| False
 | |
| >>> type(bb1)
 | |
| <class 'bool'>
 | |
| #7.2
 | |
| >>> ii1=-1234567890;ii1;type(ii1)
 | |
| -1234567890
 | |
| <class 'int'>
 | |
| >>> ff1=-8.9876e-12;ff1;type(ff1)
 | |
| -8.9876e-12
 | |
| <class 'float'>
 | |
| >>> dv1=0b1101010;dv1;type(dv1)
 | |
| 106
 | |
| <class 'int'>
 | |
| >>> vsm1=0o52765;vsm1;type(vsm1)
 | |
| 22005
 | |
| <class 'int'>
 | |
| >>> shest1=0x7109af6;shest1;type(shest1)
 | |
| 118528758
 | |
| <class 'int'>
 | |
| >>> cc1=2-3j;cc1;type(cc1)
 | |
| (2-3j)
 | |
| <class 'complex'>
 | |
| >>> a=3.67;b=-0.45;cc2=complex(a,b);cc2;type(cc2)
 | |
| (3.67-0.45j)
 | |
| <class 'complex'>
 | |
| #7.3
 | |
| >>> ss1='Это - строка символов';ss1
 | |
| 'Это - строка символов'
 | |
| >>> ss1="Это - строка символов";ss1
 | |
| 'Это - строка символов'
 | |
| >>> ss1a="Это - \" строка символов \", \n \t выводимая на двух сторонах"; print(ss1a)
 | |
| Это - " строка символов ", 
 | |
|  	 выводимая на двух сторонах
 | |
| >>> ss1b='Меня зовут: \n Кузьменко Е.А.'; print(ss1b)
 | |
| Меня зовут: 
 | |
|  Кузьменко Е.А.
 | |
| >>> mnogo="""Нетрудно заметить, что в результате операции над числами разных типов получается число, имеющее более сложный тип из тех, которые учавствуют в операции."""; print(mnogo)
 | |
| Нетрудно заметить, что в результате операции над числами разных типов получается число, имеющее более сложный тип из тех, которые учавствуют в операции.
 | |
| >>> ss1
 | |
| 'Это - строка символов'
 | |
| >>> ss1[0]
 | |
| 'Э'
 | |
| >>> ss1[8]
 | |
| 'р'
 | |
| >>> ss1[-2]
 | |
| 'о'
 | |
| >>> ss1[6:9]
 | |
| 'стр'
 | |
| >>> ss1[13:]
 | |
| 'символов'
 | |
| >>> ss1[:13]
 | |
| 'Это - строка '
 | |
| >>> ss1[5:-8]
 | |
| ' строка '
 | |
| >>> ss1[3:17:2]
 | |
| '  тоасм'
 | |
| >>> ss1[4]='='
 | |
| Traceback (most recent call last):
 | |
|   File "<pyshell#120>", line 1, in <module>
 | |
|     ss1[4]='='
 | |
| TypeError: 'str' object does not support item assignment
 | |
| >>> ss1=ss1[:4]+'='+ss1[5:];ss1
 | |
| 'Это = строка символов'
 | |
| #Примеры с ss1b
 | |
| >>> print(ss1b)
 | |
| Меня зовут: 
 | |
|  Кузьменко Е.А.
 | |
| >>> ss1b
 | |
| 'Меня зовут: \n Кузьменко Е.А.'
 | |
| >>> ss1b[0]
 | |
| 'М'
 | |
| >>> ss1b[14:]
 | |
| 'Кузьменко Е.А.'
 | |
| >>> ss1b[0:15:3]
 | |
| 'Мяот\n'
 | |
| >>> ss1b1=ss1b[:10]+' : \n'+ss1b[14:];print(ss1b1)
 | |
| Меня зовут : 
 | |
| Кузьменко Е.А.
 | |
| #Объекты разных типов
 | |
| >>> x1=6-24j;x1;type(x1)
 | |
| (6-24j)
 | |
| <class 'complex'>
 | |
| >>> x2=0.14e-13;x2;type(x2)
 | |
| 1.4e-14
 | |
| <class 'float'>
 | |
| >>> x3=0b0101;x3;type(x3)
 | |
| 5
 | |
| <class 'int'>
 | |
| >>> x4=True;x4;type(x4)
 | |
| True
 | |
| <class 'bool'>
 | |
| >>> x5=None;x5;type(x5)
 | |
| <class 'NoneType'>
 | |
| 
 | |
| #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] #Начииная от 8 элемента с конца и заканчивая последним значением с шагом 2
 | |
| [0, 1, 1, 1]
 | |
| >>> spis1[1]='Список';spis1
 | |
| [111, 'Список', (5-9j)]
 | |
| >>> len(spis1)
 | |
| 3
 | |
| #Методы добавления и удаления объекта
 | |
| >>> dir()
 | |
| ['Gg1', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'bb1', 'bb2', 'builtins', 'cc1', 'cc2', 'dv1', 'f', 'ff1', 'gg1', 'hh1', 'ii1', 'key', 'keyword', 'list1', 'list2', 'list3', 'mnogo', 'n', 'os', 'rating', 'shest1', 'spis', 'spis1', 'ss1', 'ss1a', 'ss1b', 'ss1b1', 'students', 'stup', 'vsm1', 'w', 'x1', 'x2', 'x3', 'x4', 'x5', 'z', 'z1']
 | |
| >>> 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'];spis1 #Только отображается!
 | |
| [111, 'Список', (5-9j), 'New item', 'New item']
 | |
| [111, 'Список', (5-9j), 'New item']
 | |
| >>> spis1.pop(1)
 | |
| 'Список'
 | |
| >>> spis1
 | |
| [111, (5-9j), 'New item']
 | |
| >>> spis1.append(ss1b);print(spis1)
 | |
| [111, (5-9j), 'New item', 'Меня зовут: \n Кузьменко Е.А.']
 | |
| #Другие методы
 | |
| >>> spis1.insert(3,'Новый объект');spis1 #Вставляет объект на указанную позицию
 | |
| [111, (5-9j), 'New item', 'Новый объект', 'Меня зовут: \n Кузьменко Е.А.']
 | |
| >>> spis1.remove('New item');spis1 #Удаляет конкретный объект
 | |
| [111, (5-9j), 'Новый объект', 'Меня зовут: \n Кузьменко Е.А.']
 | |
| >>> spis2=['aa',123,'bb'];spis2
 | |
| ['aa', 123, 'bb']
 | |
| >>> spis1.extend(spis2);spis1 #Добавляет объекты в конец списка
 | |
| [111, (5-9j), 'Новый объект', 'Меня зовут: \n Кузьменко Е.А.', 'aa', 123, 'bb']
 | |
| >>> spis2.clear();spis2 #Очищает список
 | |
| []
 | |
| >>> spis3=[-9,2,5,0,10,-11];spis3.sort();spis3 #Сортирует по возрастанию
 | |
| [-11, -9, 0, 2, 5, 10]
 | |
| >>> spis3.sort(reverse=True);spis3 #Сортирует по убыванию
 | |
| [10, 5, 2, 0, -9, -11]
 | |
| >>> spis1.reverse();spis1 #Выписывает список в обратном порядке
 | |
| ['bb', 123, 'aa', 'Меня зовут: \n Кузьменко Е.А.', 'Новый объект', (5-9j), 111]
 | |
| >>> copy1=spis1.copy();copy2=spis3.copy();print(copy1,copy2) #Копирует список
 | |
| ['bb', 123, 'aa', 'Меня зовут: \n Кузьменко Е.А.', 'Новый объект', (5-9j), 111] [10, 5, 2, 0, -9, -11]
 | |
| >>> spis4=[1,1,0,2,4,5,5,1];spis4.count(1) #Считает сколько раз конкретный элемент вошёл в список
 | |
| 3
 | |
| >>> spis4.index(5) #Находит индекс первого вхождения "5"
 | |
| 5
 | |
| #Вложенные списки
 | |
| >>> spis2=[spis1,[4,5,6,7]];spis2
 | |
| [['bb', 123, 'aa', 'Меня зовут: \n Кузьменко Е.А.', 'Новый объект', (5-9j), 111], [4, 5, 6, 7]]
 | |
| >>> spis2[0][1] #Обращение к элементу первого списка(т.к. "0")
 | |
| 123
 | |
| >>> spis2[0][1]=78;spis2;spis1
 | |
| [['bb', 78, 'aa', 'Меня зовут: \n Кузьменко Е.А.', 'Новый объект', (5-9j), 111], [4, 5, 6, 7]]
 | |
| ['bb', 78, 'aa', 'Меня зовут: \n Кузьменко Е.А.', 'Новый объект', (5-9j), 111]
 | |
| >>> spis0=[123, 'ice cream', False, spis2];spis0
 | |
| [123, 'ice cream', False, [['bb', 78, 'aa', 'Меня зовут: \n Кузьменко Е.А.', 'Новый объект', (5-9j), 111], [4, 5, 6, 7]]]
 | |
| #8.2
 | |
| >>> 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 Кузьменко Е.А.')
 | |
| >>> kort2=kort1[:2]+kort1[3:];kort2
 | |
| (222, 'Kortezh', 1, 2, 'Меня зовут: \n Кузьменко Е.А.')
 | |
| >>> kort1.index(2);kort1 #Первое появление двойки
 | |
| 4
 | |
| >>> kort1.count(222)
 | |
| 1
 | |
| >>> kort1[2]=90;kort1 #Нельзя изменить кортеж
 | |
| Traceback (most recent call last):
 | |
|   File "<pyshell#207>", line 1, in <module>
 | |
|     kort1[2]=90;kort1
 | |
| TypeError: 'tuple' object does not support item assignment
 | |
| 
 | |
| >>> kort3=(16,'boo',[1,2,"aa"],(2,"bb",2));kort3
 | |
| (16, 'boo', [1, 2, 'aa'], (2, 'bb', 2))
 | |
| #8.3
 | |
| >>> 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={'statics':dic2,'POAS':['base','elementary','programming']};dic3
 | |
| {'statics': {1: 'mean', 2: 'standart deviation', 3: 'correlation'}, 'POAS': ['base', 'elementary', 'programming']}
 | |
| >>> 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 Кузьменко Е.А.'}
 | |
| 
 | |
| >>> kort11=(2,6,'sa',True,False,12,1);kort11
 | |
| (2, 6, 'sa', True, False, 12, 1)
 | |
| >>> spis11=[2,'oo','bb',3,5];spis11
 | |
| [2, 'oo', 'bb', 3, 5]
 | |
| >>> dic11=dict(zip(kort11,spis11));dic11
 | |
| {2: 2, 6: 'oo', 'sa': 'bb', True: 3, False: 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]
 | |
| 
 | |
| #8.4
 | |
| >>> mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'};mnoz1
 | |
| {'двигатель', 'микропроцессор', 'линия связи', 'датчик'}
 | |
| >>> len(mnoz1)
 | |
| 4
 | |
| >>> 'датчик' in mnoz1
 | |
| True
 | |
| >>> mnoz1.add('реле');mnoz1
 | |
| {'двигатель', 'микропроцессор', 'реле', 'линия связи', 'датчик'}
 | |
| >>> mnoz1.remove('линия связи');mnoz1
 | |
| {'двигатель', 'микропроцессор', 'реле', 'датчик'}
 | |
| >>> mnoz2={4.12,'rr',True,True,2,2,3.2,'rr','rr',(1,2)};mnoz2
 | |
| {True, 2, 3.2, (1, 2), 4.12, 'rr'}
 | |
| >>> len(mnoz2)
 | |
| 6
 | |
| >>> 2 in mnoz2
 | |
| True
 | |
| >>> 3 in mnoz2
 | |
| False
 | |
| >>> mnoz2.add('oo');mnoz2
 | |
| {True, 2, 3.2, (1, 2), 4.12, 'oo', 'rr'}
 | |
| >>> mnoz2.remove(3.2);mnoz2
 | |
| {True, 2, (1, 2), 4.12, 'oo', 'rr'}
 | |
| 
 | |
| #9
 | |
| #Завершение работы exit()
 |