L
L
lemonlimelike2020-07-10 20:37:10
Python
lemonlimelike, 2020-07-10 20:37:10

How to optimize a function?

Hello! Here is my function code:

def wrap_up_in_file(window,file_input):
    wbf = Workbook()
    ws = wbf.active

    try:
    	list_items = get_list_data_panda(file_input)
    	articul = ''
    	for i,item in enumerate(list_items):
    		count_item = 0
    		window['out'].Update(value=f'{i}/{len(list_items)}')
    		for j,item_j in enumerate(list_items):
    			if  item['idnp'] == item_j['idnp'] and item['brand'] == item_j['brand'] and item['price'] == item_j['price']: # проверка если найденные записи совпадают
    				count_item += 1 # счетчик кол-во записей
    		if count_item != 0:
    			if articul != item['idnp']: # Эта проверка нужна чтоб не было дубликатов в файле
    				ws.append([item['idnp'],item['title'],item['brand'],count_item,item['price']])
    				articul = item['idnp']
    	window['out'].Update(value='Файл сохраняется. Ждите')
    	wbf.save(filename=f"{file_input}-result.xlsx")
    	window['out'].Update(value='Загрузка завершена')
    except Exception as e:
    	window['out'].Update(value='Произошла ошибка, смотрите логи')
    	with open('log.info','a') as file_log:
    		file_log.write(f'Error with file: {e.args}')


I am developing a graphical user interface. The function accepts a GUI window and a path to a file.
list_items returns a list of strings that become objects from this file.
Example of data from a file
5f08a65ba1c82737233304.png

This function should look for similar records, count their number and write to the file one line with the number of these records. That is, from 10 records to make one.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2020-07-10
@SoreMix

Save the products to a dictionary, where the key is the product ID and the value is the data dictionary (title, brand, etc.). There, one of the parameters, add a counter for the number of identical products. And in the output, write
Must work

def wrap_up_in_file(window,file_input):
    wbf = Workbook()
    ws = wbf.active

    all_items = {}

    try:
      list_items = get_list_data_panda(file_input)
      articul = ''
      for i,item in enumerate(list_items):
        count_item = 0
        window['out'].Update(value=f'{i}/{len(list_items)}')
        for j,item_j in enumerate(list_items):
          if  item['idnp'] == item_j['idnp'] and item['brand'] == item_j['brand'] and item['price'] == item_j['price']: # проверка если найденные записи совпадают
            count_item += 1 # счетчик кол-во записей
        if count_item != 0:
          if articul != item['idnp']: # Эта проверка нужна чтоб не было дубликатов в файле
            if item['idnp'] in all_items:
              all_items[item['idnp']]['total'] += 1
            else:
              all_items[item['idnp']] = {'title': item['title'], 'brand': item['brand'], 'count_item': count_item, 'price': item['price'], 'total': 0}
            articul = item['idnp']
      for idnp, value in all_items.items():
        ws.append([idnp,value['title'],value['brand'],value['count_item'],value['price'],value['total']])
      window['out'].Update(value='Файл сохраняется. Ждите')
      wbf.save(filename=f"{file_input}-result.xlsx")
      window['out'].Update(value='Загрузка завершена')
    except Exception as e:
      window['out'].Update(value='Произошла ошибка, смотрите логи')
      with open('log.info','a') as file_log:
        file_log.write(f'Error with file: {e.args}')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question