Python: grouping items already in a list and reverse them

Viewed 88

I have a binary file likes this:

00 01 02 04 03 03 03 03 00 05 06 03 03 03 03 03 00 07 03 03 03 03 03 03 ...

and I would like to make groups of 8 items each

[00 01 02 04 03 03 03 03] [00 05 06 03 03 03 03 03] [00 07 03 03 03 03 03 03]...

and then reverse the items inside each group like this:

[03 03 03 03 04 02 01 00] [03 03 03 03 03 06 05 00] [03 03 03 03 03 03 07 00]

I tried reverse() but it reverse all the list.

I've imagined something like that: in a loop I should count until 8 (or 7), make a group, reverse it, and then increment the row, count 8, reverse and so on but I am not able to code that.

I have tried

i=0
for item in (list_reverse):
    i+=1
    if i>8:
        list_reverse.reverse()
        i=0

but it doesn't work.

Maybe I should try a nested loop?

2 Answers

.split() the strings, then loop through it.

t = """00 01 02 04 03 03 03 03
00 05 06 03 03 03 03 03
00 07 03 03 03 03 03 03"""
out = ""
lines = t.split("\n")
for n, line in enumerate(lines):
    lst = line.split(" ")
    c = 0
    reversed_lst = ""
    while c < len(lst):
        reversed_lst += (lst[len(lst)- c -1]) + " "; c+=1 
    if n != len(lines) - 1:
        out += reversed_lst + "\n"
    else:
        out += reversed_lst
print(out)      

Output:

03 03 03 03 04 02 01 00 
03 03 03 03 03 06 05 00 
03 03 03 03 03 03 07 00 

This is a good usecase for Python's builtin bytearray. First, you can open the binary input file and use a bytearray to store its contents:

with open("binary.file", "rb") as f:
    bytes = bytearray(f.read())

Then, we'll use your algorithm to loop over the bytes and store them in a variable called group (which is also a bytearray) every 8 iterations:

i = 0
groups = []
group = bytearray()
for byte in bytes:
    i += 1
    group.append(byte)
    if i == 8:
        groups.append(group)
        i = 0
        group = bytearray()

Just as quick sanity check, test the value of variable i because if it's not zero by now the final group would be less than 8 bytes long:

if i != 0:
    raise EOFError("Input file does not align to 8 byte boundary!")

Finally, we'll reverse each group and print the output:

for group in groups:
    group.reverse()

print(groups)

Depending on your usecase, you could also concatenate the reversed bytes and store them in another file or even overwrite the same file. Although my guess is if you would do that to any ordinary binary files like a JPEG or an EXE you will break them completely. Luckily, you could run the program again to restore them!

Related