For sake of learning i opt for not using any additional libraries.
Goal of this algorithm to break lit lst into chunks 8 records each.
And additionally load the values from dictionary dct for records of lst 1-8, 9-16, 17-24.
Trying to avoid unnecessary for loops when possible, i come up with this solution.
dct = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight'}
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
loop = 0
for record in lst:
print(f'record id: {record:<10} dct id: {record-loop:<10} dct value: {dct.get(record - loop)}')
if record % 8 == 0:
loop += 8
print('--- loop finished ---')
this output
record id: 1 dct id: 1 dct value: one
record id: 2 dct id: 2 dct value: two
record id: 3 dct id: 3 dct value: three
record id: 4 dct id: 4 dct value: four
record id: 5 dct id: 5 dct value: five
record id: 6 dct id: 6 dct value: six
record id: 7 dct id: 7 dct value: seven
record id: 8 dct id: 8 dct value: eight
--- loop finished ---
record id: 9 dct id: 1 dct value: one
record id: 10 dct id: 2 dct value: two
record id: 11 dct id: 3 dct value: three
record id: 12 dct id: 4 dct value: four
record id: 13 dct id: 5 dct value: five
record id: 14 dct id: 6 dct value: six
record id: 15 dct id: 7 dct value: seven
record id: 16 dct id: 8 dct value: eight
--- loop finished ---
record id: 17 dct id: 1 dct value: one
record id: 18 dct id: 2 dct value: two
record id: 19 dct id: 3 dct value: three
record id: 20 dct id: 4 dct value: four
record id: 21 dct id: 5 dct value: five
record id: 22 dct id: 6 dct value: six
record id: 23 dct id: 7 dct value: seven
record id: 24 dct id: 8 dct value: eight
--- loop finished ---
Can someone with more mathematical experience suggest how can i get rid of variable loop altogether along with this section
if record % 8 == 0:
loop += 8
and instead use some mathematical formula instead of record - loop
If i am simply using dct.get(record % 8) i am getting wrong result since record % 8 produces this code
1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0
I need
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
Of course i could use a barbaric fix like this ((record - 1) % 8) + 1 to make it work, but i am sure there's more clean and more readable way of doing it.
I think you may have a misunderstanding about how loops work.
Each loop finishes at the bottom of the code block.
In the case of your lst, you're going to make 24 loops.
However, it would appear you're not looking for the loop number but rather a counter of 1-8.