Показаны сообщения с ярлыком List. Показать все сообщения
Показаны сообщения с ярлыком List. Показать все сообщения

суббота, 5 июня 2021 г.

Самые полезные ФУНКЦИИ Пайтона

 1) 

PRINT - выводит на печать переменную, указанную в скобках

print(average) 



2) 

LEN - посчитать количество элементов в списке

students_grades = [12, 10, 11, 10,12]
number_st = len(students_grades)
print(number_st)
Рез-т
5


3) 
STR, INT, FLOAT
- задает переменной указанный тип данных
x = 4   #Integer
y = "5" #String
calculate = int(y) - x #Делаем Y числом (integer), чтобы возможно было посчитать
print(calculate)


4)
LIST - преобразует в список

students_grade = [12, 10, 9, 12, 11]
squar = (n**2 for n in students_grade) # Все элементы списка возводим во вторую степень
list_squar = list(squar) # Если не преобразовать результат в список
                            - то выдаст ошибку
print(list_squar)

Рез-т
[144, 100, 81, 144, 121]


5) 
TUPLE - Создает кортеж


6) 
DICT - Создает словарь

Вариант 1
my_list = [('name','Rudy'),('surname','Tey3oyj5o3'),('country','Montenegro')]
rudy_data = dict(my_list)
print(rudy_data)

Рез-т
{'name': 'Rudy', 'surname': 'Tey3oyj5o3', 'country': 'Montenegro'}


Вариант 2
rudy_data = dict(name='Rudy', surname='Tey3oyj5o3', country='Montenegro')
print(rudy_data)
Рез-т
{'name': 'Rudy', 'surname': 'Tey3oyj5o3', 'country': 'Montenegro'}


7)
SET - НАБОР

Выстраивает все элементы списка в определенном порядке, исключает повторяющиеся элементы

old_list = [2, 4, 59, 48, 3, 2]
new_list = set(old_list)
print(new_list)
Рез-т
{2, 3, 4, 48, 59}


суббота, 16 января 2021 г.

Операции с LIST (Список)

 dir (list)


 |  list(iterable=(), /) - Имеет возможность прохода по всем элементам списка.

 |  

 |  Built-in mutable sequence. - Встроенный в Python тип данных - последовательность, которая может быть изменена.

 |  

 |  Methods defined here: (Методы, которые можно использовать со СПИСКОМ)

 |  

 |  __add__(self, value, /)

 |      Return self+value - Добавляет элемент или список элементов в конец существующего списка.

- Пример

list = [445, 1, 928, 435.3, 0, 3, 1]
new_list = list.__add__([222, 'def', 4444])
print(new_list)
- Результат
[445, 1, 928, 435.3, 0, 3, 1, 222, 'def', 4444]

 |  

 |  __contains__(self, key, /)

 |      Return key in self. - Если элемент (key) обнаружен в списке, то возвращает True, если нет - то False.

- Привет

list = [445, 1, 928, 435.3, 0, 3, 1]
if_contains_element = list.__contains__(1)
print(if_contains_element)
- Результат 
True

 |  

 |  __delitem__(self, key, /)

 |      Delete self[key]. - Удаляет элемент по указанному индексу (key)

- Пример

list = [445, 1, 928, 435.3, 0, 3, 1]
list.__delitem__(3)
print(list)
- Результат
[445, 1, 928, 0, 3, 1]

 |  

 |  __eq__(self, value, /)

 |      Return self==value - Проверяет список value является ли идентичным данному списку. Если списки одинаковы (одинаковым должен быть и порядок) - то возвращает значение True,  если списки не идентичны, то возвращает False.

- Пример 1

list = [445, 0, 928, 435.3, 1, 3, 1]
are_lists_equal = list.__eq__([445, 0, 928, 435.3, 1, 3, 1])
print(are_lists_equal)
- Результат
True
- Пример 2
list = [445, 0, 928, 435.3, 1, 3, 1]
are_lists_equal = list.__eq__([1])
print(are_lists_equal)
- Результат
False

 |  

 |  __ge__(self, value, /)

 |      Return self>=value.

 |  

 |  __getattribute__(self, name, /)

 |      Return getattr(self, name).

 |  

 |  __getitem__(...)

 |      x.__getitem__(y) <==> x[y]

 |  

 |  __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) - Возвращает количество элементов в списке

- Пример

list = [445, 0, 928, 435.3, 1, 3]
length = list.__len__()
print(length)
- Результат
6

 |  

 |  __lt__(self, value, /)

 |      Return self<value.


 |  

 |  __mul__(self, value, /)

 |      Return self*value. - Создает новый список, который включает в себя старый список столько раз, сколько указано в value - по сути умножает список на value

-  Пример

list = [445, 0, 928, 435.3, 1, 3]
new_list = list.__mul__(2)
print(new_list)
- Результат
[445, 0, 928, 435.3, 1, 3, 445, 0, 928, 435.3, 1, 3]

 |  

 |  __ne__(self, value, /)

 |      Return self!=value. - Возвращает True, если список value не равен данному списку, возвращает False - если списки одинаковые

- Пример 1

list = [445, 0, 928, 435.3, 1, 3]
new_list = list.__ne__([445, 0, 928, 435.3, 1, 3])
print(new_list)
- Результат
False

- Пример 2

list = [445, 0, 928, 435.3, 1, 3]
new_list = list.__ne__(["egwg", 1, 333])
print(new_list)
- Результат
True

 |  

 |  __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. - Заменяет элемент с индексом key на значение value.

- Пример

list = [445, 0, 928, 435.3, 1, 3]
list.__setitem__(2, "frgj")
print(list)
-Результат
[445, 0, 'frgj', 435.3, 1, 3]


 |  

 |  __sizeof__(self, /)

 |      Return the size of the list in memory, in bytes - Возвращает размер списка с байтах.

- Пример

list = [445, 0, 928, 435.3, 1, 3]
size = list.__sizeof__()
print(size)
- Результат
88

 |  

 |  append(self, object, /)

 |      Append object to the end of the list (Добавляет новый элемент в конец списка). 

- Пример:

list = [1, 443, 928, 435.3]
list.append(13)
print(list)
- Результат:
[1, 443, 928, 435.3, 13]

 |  

 |  clear(self, /)

 |      Remove all items from list (Очищает список).

- Пример:

list = [1, 443, 928, 435.3]
list.clear()
print(list)
- Результат:
[] - пустой список

 |  

 |  copy(self, /)

 |      Return a shallow copy of the list.

 |  


 |  count(self, value, /)

 |      Return number of occurrences of value (Считает сколько раз определенный элемент встерчается в последовательности).

- Пример:

list = [1, 443, 928, 435.3, 1, 324, 4, 1]
number_occurancies = list.count(1)
print(number_occurancies)
- Результат:
3

 |  

 |  extend(self, iterable, /)

 |      Extend list by appending elements from the iterable (Добавляет в текущий список элементы из списка iterable.

- Пример:

list = [1, 443, 928, 435.3, 0]
list.extend([4, 22])
print(list)
- Результат:
[1, 443, 928, 435.3, 0, 4, 22]

 |  

 |  index(self, value, start=0, stop=9223372036854775807, /)

 |      Return first index of value. -  Ищет элемент value и выдает индекс первого найденного элемента.
Если в скобках указано только одно значение, то ищет это значение по всему списку.

 |      Raises ValueError if the value is not present. - Возвращает сообщение об ошибке, что элемент не найден.

- Пример:

ValueError: 42357 is not in list


- Пример 1:

list = [1, 443, 928, 435.3, 0, 3, 1, 0 , 46, 24]
first_index = list.index(1)
print(first_index)
- Результат:
0 - Так как элементы списка считаются с нуля (то есть первый элемент имеет индекс 0, второй - 1, третий - 2 и так далее).

Если в скобках указано 2 или 3 элемент: первый элемент (value) - это искомое значение, второй (start) - индекс с которого
 надо начать поиск, третий (stop) - последний элемент в поиске)
При этом начальный элемент (start) включается в поиск, а последний (stop) - нет.

- Пример 2:

list = [445, 1, 928, 435.3, 0, 3, 1, 0 , 46, 24]
first_index = list.index(1, 1, 7)
print(first_index)
- Результат:
1 - Единица имеет индекс 1 в списке, поиск с первого элемента (включительно) до седьмого элемента (не включительно).

 |  

 |  insert(self, index, object, /)

 |      Insert object before index. - Добавляет в список элемент object перед указанным индексом.

- Пример

list = [445, 1, 928, 435.3, 0, 3, 1, 0 , 46, 24]
list.insert(1, 4857)
print(list)
- Результат
[445, 4857, 1, 928, 435.3, 0, 3, 1, 0, 46, 24]

 |  

 |  pop(self, index=-1, /)

 |      Remove and return item at index (default last). - Удаляет элемент из списка по указанному индексу.

 |      Raises IndexError if list is empty or index is out of range. - Отображает ошибку, если список пустой или не содержит запрашиваемый индекс.

- Пример 2

list = [445, 1, 928, 435.3, 0, 3, 1, 0 , 46, 24]
list.pop(2)
print(list)
- Результат
[445, 1, 435.3, 0, 3, 1, 0, 46, 24]

Возвращает элемент по индексу. Но при этом элемент из списка удаляется
- Пример 2
list = [445, 1, 928, 435.3, 0, 3, 1, 0 , 46, 24]
element = list.pop(2)
print(element)
print(list)
- Результат
928
[445, 1, 435.3, 0, 3, 1, 0, 46, 24]

 |  

 |  remove(self, value, /)

 |      Remove first occurrence of value. - Удаляет первый элемент, который попадется в списке с указнным значением (value)

 |      Raises ValueError if the value is not present. - Выдает ошибку, если элемента нет в списке

- Пример

list = [445, 1, 928, 435.3, 0, 3, 1, 0 , 3, 46, 24]
list.remove(3)
print(list)
Результат
[445, 1, 928, 435.3, 0, 1, 0, 3, 46, 24]

 |  

 |  reverse(self, /)

 |      Reverse *IN PLACE*. - Переворачивает список - в итоге список начинается с последнего элемента и заканчивается первым.

- Пример

list = [445, 1, 928, 435.3, 0, 3, 1, 0 , 3, 46, 24]
list.reverse()
print(list)
- Результат
[24, 46, 3, 0, 1, 3, 0, 435.3, 928, 1, 445]

 |  

 |  sort(self, /, *, key=None, reverse=False)

 |      Stable sort *IN PLACE* - Сортирует список  - по умолчанию (если никакие дополнительные параметры не указаны) от меньшего элемента к большему (для числовых значений)

- Пример 1

list = [445, 1, 928, 435.3, 0, 3, 1, 0 , 3, 46, 24]
list.sort()
print(list)
- Результат
[0, 0, 1, 1, 3, 3, 24, 46, 435.3, 445, 928]

 |  

 |  ----------------------------------------------------------------------

 |  Static methods defined here:

 |  

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 |  


суббота, 23 мая 2020 г.

Тип данных - Словарь (Dictionary)

Иногда обычного списка недостаточно.
Например мы имеем список с оценками студентов за экзамен

student_grades = [12, 5, 6, 10, 11, 10, 9, 8, 7]

Но имея этот список мы не знаем какой студент получил какую оценку. Чтобы привязать имя студента к оценке, мы используем Dictionary (Словарь):

student_grades = {"Marie": 12, "John": 5, "Max": 6, "Michael": 10, "Anna": 11}


Marie - это ключ (key)
12 - это значение (value)


МЕТОД 1 - VALUES()

Используется, чтобы получить значения (value) из словаря (dictionary).

student_grades.values()

Получаем список только из значений:
dict_values = ([12, 5, 6, 10, 11])

Если нам нужно посчитать СРЕДНЮЮ оценку

sum = sum(student_grades.values())

length = len(student_grades)

average = sum/length

print(average)


МЕТОД 2 - KEYS()


student_grades.keys()

dict_keys = (['Marie', 'John', 'Max', 'Michael', 'Anna'])



Все методы, которые мы можем использовать с переменной


['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']


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)
 |  
 |  Built-in subclasses:
 |      StgDict
 |  
 |  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__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __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__(...)
 |      D.__sizeof__() -> size of D in memory, in bytes
 |  
 |  clear(...)
 |      D.clear() -> None.  Remove all items from D.
 |  
 |  copy(...)
 |      D.copy() -> a shallow copy of D
 |  
 |  get(self, key, default=None, /)
 |      Return the value for key if key is in the dictionary, else default.

Пример

Вывести оценку определенного студента


student_grades = {"Marie": 12, "John": 5, "Max": 6, "Michael": 10, "Anna": 11}

marie_grade = student_grades.get("Marie")

print(marie_grade)



 |  
 |  items(...)
 |      D.items() -> a set-like object providing a view on D's items
 |  
 |  keys(...)
 |      D.keys() -> a set-like object providing a view on D's keys
 |  
 |  pop(...)
 |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 |      
 |      If key is not found, default is returned if given, otherwise KeyError is raised
 |  
 |  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 dict/iterable E and F.
 |      If E is present and has a .keys() method, then does:  for k in E: 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(...)
 |      D.values() -> an object providing a view on D's values
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  __class_getitem__(...) from builtins.type
 |      See PEP 585
 |  
 |  fromkeys(iterable, value=None, /) from builtins.type
 |      Create a new dictionary with keys from iterable and values set to value.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None



Посчитать сколько раз элемент встречается в списке

Например, нам надо посчитать сколько студентов с балом 10 в списке.

student_grades list содержит оценки студентов за экзамер.

Функция COUNT() считает сколько раз определенный элемент попадается в списке.




student_grades = [9.1, 8.8, 10.0, 7.7, 6.8, 8.0, 10.0, 8.1, 10.0, 9.9]
n = student_grades.count(10.0)
print(n)

Результат:
3

суббота, 16 мая 2020 г.

Как посчитать среднее значение в списке List



Предположим, мы имеем список с баллами студентов от 1 до 12 в списке list.

student_grades = [12, 10, 11, 12, 10, 8, 11, 12, 7, 11]

Нужно посчитать среднее значение оценок студентов.

Для этого сначала считаем сумму всех оценок студентов:
sum = sum(student_grades)

Считаем количство элементов (студентов) в списке:
quantity = len(student_grades)


Чтобы найти среднее значение sum делим на quantity.

____________________

student_grades = [12, 10, 11, 12, 10, 8, 11, 12, 7, 11]

sum = sum(student_grades)
quantity = len(student_grades)

average = sum/quantity

print(average)
_________



Запускаем файл через Терминал
python3.7 my_folder/my_file.py

Результат:
10.4





Функции в Python. Как просмотреть весь список доступных функций и переменных.

Чтобы вывести на экран список всех доступных функций и переменных, в Терминале набираем:

>>> 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', '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']

Мы видим тут кроме функций и все типы переменных -  О типах переменных читайте ТУТ

четверг, 14 мая 2020 г.

Методы для всех типов данных. Как посмотреть весь набор методов. Примеры использования

Итак, есть 6 основных типов дынных:
- string,
- integer,
- float,
- boolean,
- list,
- dictionary,
- tuple.

Чтобы посмотреть все методы, которые мы можем применить к определенному типу данных, в командной строке набираем:


dir (str)


Результат:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']


  • capitalize - делает первую букву заглавной


>>> str.capitalize("hello")
или
>>> "hello".capitalize()

Результат:   'Hello'


  • title - делает первую букву заглавной (по сути тоже самое, что и capitalize)


>>> str.title('hello')
Результат:   'Hello'



  • upper - пишет все слово заглавными буквами


>>> str.upper('hello')
>>> 'hello'.upper()

Результат:   'HELLO'

  • lower - пишет все слово маленькими буквами
username = "Python3"
lower = username.lower()
print(lower)


Пример с count - тут



dir(int)


['__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__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']


dir(float)


['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']


dir(list)


['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

append - Добавить элемент в список

Пример с count - тут


dir (dict)  - Dictionary


['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']



dir(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.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return 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.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.




понедельник, 11 мая 2020 г.

Типы переменных в Python - String, Integer, Float, Boolean, List, Dictionary, Tuple.

Существуют несколько типов переменных в Пайтон:

1.

STRING (str)

- Это строка. Чтобы задать этот тип, нужно данные взять в ковычки (не важно одинарные или двойные)
a = "text"

dir(str) - Чтобы вывести весь список доступных для данного типа данных функций.

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']



2.

INTEGER (int)

- Целое число. Задается без ковычек.
b = 10

dir(int)

['__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__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']



3.

FLOAT

- Это дробное число. Задается без ковычек с точкой.
c = 10.2

dir(float)

['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']


4.

BOOLEAN (bool) 

- Значение этой переменной может быть только TRUE или FALSE.
d = True

dir(bool)

['__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__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']


5.

LIST [Список] 

mutable (может быть изменен) в отличии от Tuple.

- это список переменных. Он может содержать любое количество переменных разного типа (в примере 4 переменные разного типа).
list = [10, 10.4, "text", "24759"]

List также может содержать другой list
list = [0, 10.4, "text", [8, 'efhe']]

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']


RANGE 

- эта функция позволяет создать список с указанным диапазомом.
list(range(1, 6))
Это то же самое, что:
[1, 2, 3, 4, 5]
Обратите внимание, что 6 не попадает в список!

Можно указать еще ШАГ в качестве третьего аргумента
list(range(1, 6, 2))
[1, 3, 5]
то есть это все числа в переделах диапазона с 1 до 5 с шагом 2


При необходимости, можно изменить тип переменной в программе.
Например, программа-калькулятор запрашивает числа, чтобы потом выполнить действия с ними... Для этого мы будет использовать функцию INPUT, но она воспринимает всегда данные как строку.

a = input("Введите число A")
b = input("Введите число B")

Предположим пользователь указал a = 5, b = 3.
Пользователь вводит числa. Но если мы сложим их сейчас, то получим:
c = a + b = 53

Потому что 5 и 3 - это текст.

Чтобы в программе переделать текст на числа, добавляем нужный нам формат - float или integer.

a = float (input ("Введите число A:   "))
b = float (input ("Введите число B:   "))
c = a + b
print ("Результат = " + str(c))

Результат нам надо было переделать обратно в строку для печати. Поэтому в функции print - указываем - str(c)


APPEND - Добавляет 1 элемент в список

list = [10, 10.4, "text", "24759"]
list.append(1)
print(list)
Результат
[10, 10.4, 'text', '24759', 1]

MAX - Найти максимальное значение в списке

student_grades = [9.1, 8.8, 7.5]

max_value = max(student_grades) print(max_value)

Результат:
9.1



6.

DICTIONARY (dict) {Словарь}


student_grades = {"Marie": 12, "John": 5, "Max": 6, "Michael": 10, "Anna": 11}

Про словари можете почитать в СТАТЬЕ.

Словарь может содержать внутри себя любые элементы. 
Пример - Словарь содержит 3 переменные с кортежем данных для каждого времени суток).

day_temperatures = {'morning':(1.3, 2.1, 3.0), 'noon':(19.6, 34.4, 1.2), 'evening':(2.3, 4.4, 4.7)}

dir(dict)

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']



7.

TUPLE (Кортеж) 

- immutable в отличии от List.
Это значит, что кортеж не может быть изменен (не может мутировать)

temperature = (10, 24, 5, 19, 2)

Кортеж может содержать внутри себя любые другие переменные.
color_codes = (("green", "red", "white"), (1,2), (3974, "uougo"))  
-  Кортеж содержит внутри себя 3 других кортежа

dir(tuple)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']


HELP


Можно почитать документацию по командам или переменным в Python, используя HELP

help(str) 

help(str.replace) 

replace(self, old, new, count=-1, /)
    Return a copy with all occurrences of substring old replaced by new.
    
      count
        Maximum number of occurrences to replace.
        -1 (the default value) means replace all occurrences.

help(dict.values)

values(...)
    D.values() -> an object providing a view on D's values



Самые полезные ФУНКЦИИ Пайтона

 1)  PRINT - выводит на печать переменную, указанную в скобках print (average)   2)  LEN - посчитать количество элементов в списке student...