PyDev console: starting.
Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32
a = ['[<rect(32, 16, 20, 20)>, <rect(48, 210, 20, 20)>, <rect(232, 178, 20, 20)>, <rect(362, 136, 20, 20)>, <rect(264, 183, 20, 20)>, <rect(144, 262, 20, 20)>, <rect(359, 140, 20, 20)>, <rect(287, 147, 20, 20)>, <rect(122, 266, 20, 20)>, <rect(368, 78, 20, 20)>, <rect(87, 32, 20, 20)>, <rect(46, 334, 20, 20)>, <rect(36, 4, 20, 20)>, <rect(129, 266, 20, 20)>, <rect(95, 72, 20, 20)>, <rect(211, 369, 20, 20)>, <rect(108, 379, 20, 20)>, <rect(277, 337, 20, 20)>, <rect(22, 262, 20, 20)>, <rect(212, 368, 20, 20)>]']
import re
rr = re.compile(r'<rect\((\d+), (\d+), (\d+), (\d+)\)>')
rr.findall(a[0])
[('32', '16', '20', '20'), ('48', '210', '20', '20'), ('232', '178', '20', '20'), ('362', '136', '20', '20'), ('264', '183', '20', '20'), ('144', '262', '20', '20'), ('359', '140', '20', '20'), ('287', '147', '20', '20'), ('122', '266', '20', '20'), ('368', '78', '20', '20'), ('87', '32', '20', '20'), ('46', '334', '20', '20'), ('36', '4', '20', '20'), ('129', '266', '20', '20'), ('95', '72', '20', '20'), ('211', '369', '20', '20'), ('108', '379', '20', '20'), ('277', '337', '20', '20'), ('22', '262', '20', '20'), ('212', '368', '20', '20')]
import random
a = list(range(10000))
while s := (sum(l := [random.choice(a) for _ in range(6)])) != 10000:
print(s, l)
vertex: ModelVertex = ModelVertex()
vertex: ModelVertex = field(default_factory=ModelVertex)
from typing import List
class Menu:
storage: List = []
def __str__(self):
return str(self.storage)
def __getattr__(self, item):
if item not in self.storage.__dir__():
raise AttributeError(f'Нет такого метода {item}')
return getattr(self.storage, item)
def append(self, item):
self.storage.append(item)
menu = Menu()
menu.append(10)
print(menu)
menu.extend((11, 12,))
print(menu)
menu.not_method(10)
from collections import defaultdict
from pprint import pprint
<spoiler title="values">
d =[{'Ref_Key': '33ed0832-9697-11eb-8568-18c04d0357e4', 'DataVersion': 'AAABRgAAAAA=', 'DeletionMark': False,
'Parent_Key': 'a888a6c7-bb96-11ea-834d-f0795994df35', 'IsFolder': True, 'Code': 'СГ-000359',
'Description': '1.1. Затраты на приобретение прав на ЗУ ', 'ВидДеятельностиДляНалоговогоУчетаЗатрат': None,
'ВидРасходовНУ': None, 'РеквизитДопУпорядочивания': '12', 'Код_Добавленный': '', 'Синтека_projectId': '',
'Predefined': False, 'PredefinedDataName': '',
'Parent@navigationLinkUrl': "Catalog_СтатьиЗатрат(guid'33ed0832-9697-11eb-8568-18c04d0357e4')/Parent"},
{'Ref_Key': '33ed0834-9697-11eb-8568-18c04d0357e4', 'DataVersion': 'AAABSAAAAAA=', 'DeletionMark': False,
'Parent_Key': 'a888a6c7-bb96-11ea-834d-f0795994df35', 'IsFolder': True, 'Code': 'СГ-000361',
'Description': '1.5. Затраты на аренду ЗУ ', 'ВидДеятельностиДляНалоговогоУчетаЗатрат': None,
'ВидРасходовНУ': None, 'РеквизитДопУпорядочивания': '13', 'Код_Добавленный': '', 'Синтека_projectId': '',
'Predefined': False, 'PredefinedDataName': '',
'Parent@navigationLinkUrl': "Catalog_СтатьиЗатрат(guid'33ed0834-9697-11eb-8568-18c04d0357e4')/Parent"},
{'Ref_Key': '33ed0836-9697-11eb-8568-18c04d0357e4', 'DataVersion': 'AAABSgAAAAA=', 'DeletionMark': False,
'Parent_Key': 'a888a6c7-bb96-11ea-834d-f0795994df35', 'IsFolder': True, 'Code': 'СГ-000363',
'Description': '1.6. Затраты на изменение ВРИ.Проектирование', 'ВидДеятельностиДляНалоговогоУчетаЗатрат': None,
'ВидРасходовНУ': None, 'РеквизитДопУпорядочивания': '14', 'Код_Добавленный': '', 'Синтека_projectId': '',
'Predefined': False, 'PredefinedDataName': '',
'Parent@navigationLinkUrl': "Catalog_СтатьиЗатрат(guid'33ed0836-9697-11eb-8568-18c04d0357e4')/Parent"},
{'Ref_Key': '33ed0838-9697-11eb-8568-18c04d0357e4', 'DataVersion': 'AAABTAAAAAA=', 'DeletionMark': False,
'Parent_Key': 'a888a6c7-bb96-11ea-834d-f0795994df35', 'IsFolder': True, 'Code': 'СГ-000365',
'Description': '1.8. Прочие затраты на улучшения и содержание ЗУ',
'ВидДеятельностиДляНалоговогоУчетаЗатрат': None, 'ВидРасходовНУ': None, 'РеквизитДопУпорядочивания': '15',
'Код_Добавленный': '', 'Синтека_projectId': '', 'Predefined': False, 'PredefinedDataName': '',
'Parent@navigationLinkUrl': "Catalog_СтатьиЗатрат(guid'33ed0838-9697-11eb-8568-18c04d0357e4')/Parent"}]</spoiler>
tree = defaultdict(list)
for value in d:
tree[value['Parent_Key']].append(value)
pprint(tree)
from collections.abc import Iterable
def iterator(obj):
if isinstance(obj, Iterable):
for v in obj:
yield from iterator(v)
else:
yield obj
b = [[78, 56, 232, 12, 11, 43], 11]
a = list(iterator(b))
print(a)
[78, 56, 232, 12, 11, 43, 11]
for keys in matrix_1:
for key, values in zip(keys, matrix_2):
print([(key, value, key*value) for value in values])
[(2, 8, 16), (2, 9, 18)]
[(3, 4, 12), (3, 5, 15)]
[(4, 3, 12), (4, 6, 24)]
[(5, 8, 40), (5, 9, 45)]
[(6, 4, 24), (6, 5, 30)]
[(7, 3, 21), (7, 6, 42)]
class Example:
def __init__(self):
print('Вызов __init__')
def __enter__(self) -> 'Example':
print('Вызов __enter__')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('Вызов __exit__')
if exc_type is not None and issubclass(exc_type, Exception):
print('Тип ошибки: ', exc_type)
print('Значение ошибки: ', exc_val)
print('"След" ошибки: ', exc_tb)
return True
my_obj = Example()
with my_obj as obj:
print('Код внутри первого вызова контекст менеджера')
with my_obj as obj2:
raise Exception('Выброс исключения во вложенном (втором) вызове контекст менеджере')
print('Я обязательно выведусь...')
from collections import defaultdict
t = 0.01
mass = [
[34.224, 51],
[34.226, 1],
[34.227, 32],
[34.234, 521],
[34.236, 5],
[34.247, 24],
[34.248, 334],
[34.274, 1],
[34.274, 22],
[34.290, 321],
[34.292, 51],
[34.299, 34]
]
d = defaultdict(int)
for key, value in mass:
d[int(key / t)] += value
print([[f'{k * t:.2f}', v] for k, v in d.items()])
d = {0: [], 1: []}
for v in [-9414011, 6617441, 9673581, 4326209, -2899849, 9923397, -2291281, -5434819, 8837901, 3041829, -1378743, 3743373, 3511523, 9455891, -1351663, 4948885, 5353785, 4909097, -4585903, -6153616]:
d[v % 2].append(v)
value = d[0][0] if len(d[0]) == 1 else d[1][0]
class Caller:
def __init__(self, *args, **kwargs):
self.list_func = []
self.args = args
self.kwargs = kwargs
def __iter__(self):
for func in self.list_func:
yield f'{func.__name__}: {func(*self.args, **self.kwargs)}'
def app_func(self, func):
self.list_func.append(func)
def register_function(caller0):
def my_decorator(func):
caller0.app_func(func)
return my_decorator
caller1 = Caller(1, 2, z=5) # создаем один объект Caller'а, который хранит в себе числовые аргументы
@register_function(caller1) # регистрируем функцию в обоих объектах
def summator(x, y, z): # сама функция просто возвращает сумму аргументов
return x + y + z
@register_function(caller1) # регистрируем функцию в обоих объектах
def func_2(x, y, z): # сама функция просто возвращает сумму аргументов
return x * y * z
for result in caller1: # теперь будем лениво вызывать функции, зарегистрированные
print(result)
summator: 8
func_2: 10
async def get_url(url, session):
file_name = str(uuid.uuid4())
async with async_timeout.timeout(120):
async with session.get(url) as response:
with open(file_name, 'wb') as fd:
async for data in response.content.iter_chunked(9000):
fd.write(data)
return 'Successfully downloaded ' + file_name - вот тут вы выходите из цикла и функции и скачиваете один только блок
Вот так скачали завершили функциию
async for data in response.content.iter_chunked(9000):
fd.write(data)
print(data)
return 'Successfully downloaded ' + file_name
a = [1,2,3,3,3,4,5,6,6,6,6,6,3,3]
from itertools import groupby
new_a= []
for _, values in groupby(a):
values = list(values)
if len(values) < 3:
new_a.extend(values)
print(new_a)
[1, 2, 4, 5, 3, 3]
import re
files = ['новая папка', 'games', 'install', 'фото', 'музыка']
search = ['папка', 'фотки', 'музло']
finds = set()
chars_find = re.compile(r'\w{3}')
for file in files:
for world_search in search:
for world in chars_find.findall(world_search):
if world in file:
finds.add(file)
print(finds)
import configparser
from datetime import time
from pprint import pprint
config = configparser.ConfigParser() # создаём объекта парсера
config.read("conf.ini") # читаем конфиг
my_config_parser_dict = {s: dict(config.items(s)) for s in config.sections()}
for block in my_config_parser_dict.values():
block['bool'] = True
block['time'] = time(15, 20)
print(*block.values(), sep='|')
print()
pprint(my_config_parser_dict)
1|cam1|1-st floor|10.0.1.23|00:1A:C2:7B:00:47|True|15:20:00
2|cam2|2-nd floor|10.0.1.24|00:4A:C2:7B:10:42|True|15:20:00
3|cam3|3-rd floor|10.0.1.25|00:43:C2:7B:F0:13|True|15:20:00
{'cam1': {'area': '1-st floor',
'bool': True,
'ip': '10.0.1.23',
'mac': '00:1A:C2:7B:00:47',
'name': 'cam1',
'pos': '1',
'time': datetime.time(15, 20)},
'cam2': {'area': '2-nd floor',
'bool': True,
'ip': '10.0.1.24',
'mac': '00:4A:C2:7B:10:42',
'name': 'cam2',
'pos': '2',
'time': datetime.time(15, 20)},
'cam3': {'area': '3-rd floor',
'bool': True,
'ip': '10.0.1.25',
'mac': '00:43:C2:7B:F0:13',
'name': 'cam3',
'pos': '3',
'time': datetime.time(15, 20)}}
- вот тут вы идете по словарю, добавляете ключ в лист expected_response_text, потом в него же переприсваете словарь харкодный - что тут по вашему должно произойти?
expected_response_text=[]
for i in UA:
expected_response_text.append(i)
expected_response_text = {'user_agent': 'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','platform': 'Mobile', 'browser': 'No', 'device': 'Android'}
@pytest.mark.parametrize('agent, platform, browser, device', UA)
def test_get_user_agent(self, agent, platform, browser, device):
url = "https://playground.learnqa.ru/ajax/api/user_agent_check"
UA = {"user-agent": agent}
response = requests.get(url, headers=UA)
parsed_response = response.json()
expected_response_text = {
'user_agent': agent,
'platform': platform,
'browser': browser,
'device': device
}
print(expected_response_text)
actual_response_text = parsed_response
print(actual_response_text)
assert not (result := compare(expected_response_text, actual_response_text)), result