Search code examples
pythongrouping

Create group of three lines with Python


I have a text file with many lines like this:

aDB8786793440
bDB8978963432
cDB9898908345
dDB8908908454
eDB9083459089
fDB9082390843
gDB9083490345

I need to create groups of three, final format is less relevant as long as i can access the each group.

Desired output:

# something like this
group_1 = ["aDB8786793440", "bDB8978963432", "cDB9898908345"]
group_2 = ["dDB8908908454", "eDB9083459089", "fDB9082390843"]

# or like this
groups = [["aDB8786793440", "bDB8978963432", "cDB9898908345"], ["dDB8908908454", "eDB9083459089", "fDB9082390843"]]

Solution

  • Hope my code helps. It will create groups of 3 and will then have a final group with any remainders.

    groups = []
    
    with open('text') as f:
        f = f.readlines()
    
    for x in range(0,len(f),3):
        groups.append(f[x:3+x])
    
    print(groups)