Home > other >  How to split existing list into smaller, separate lists (without using 'groupby')?
How to split existing list into smaller, separate lists (without using 'groupby')?

Time:12-07

I have a list with 64 values, that I want to split into 8 smaller lists. This is the function I used to make the values.

def listMaker(l):
    for i in range(10):
        l.append(f"0{i}") #Makes all singles digit numbers start with 0 ('01') to make grid even length
    
    for i in range(10, 64):
        l.append(f"{i}") #prints all numbers upto 63 (for index 0-63)

I want to go from: ['1','2','3','4']

To something like [['1','2']['3','4']]

So that it can be referenced like print(l[val1][val2])

CodePudding user response:

You need to iterate over the main list, save the values into an intermediate list, when it reches the expected size, save it and use a new one

def listMaker(values, size):
    result, tmp = [], []
    for value in values:
        if len(tmp) == size:
            result.append(tmp)
            tmp = []
        tmp.append(value)

    if tmp:  # add last bucket
        result.append(tmp)
    return result


print(listMaker(range(10), 4))
# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
print(listMaker(range(20), 6))
# [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19]]

CodePudding user response:

You can use the "magic" zip-iter trick:

def listMaker(l):
    for i in range(10):
        l.append(f"0{i}") #Makes all singles digit numbers start with 0 ('01') to make grid even length
    
    for i in range(10, 64):
        l.append(f"{i}") #prints all numbers upto 63 (for index 0-63)

l = []

listMaker(l)

list2 = [list(subl) for subl in zip(*[iter(l)]*8)]

list2
# Out[133]: 
# [['00', '01', '02', '03', '04', '05', '06', '07'],
#  ['08', '09', '10', '11', '12', '13', '14', '15'],
#  ['16', '17', '18', '19', '20', '21', '22', '23'],
#  ['24', '25', '26', '27', '28', '29', '30', '31'],
#  ['32', '33', '34', '35', '36', '37', '38', '39'],
#  ['40', '41', '42', '43', '44', '45', '46', '47'],
#  ['48', '49', '50', '51', '52', '53', '54', '55'],
#  ['56', '57', '58', '59', '60', '61', '62', '63']]

CodePudding user response:

A list of sublists could be created with a list comprehension:

n = 8 #size of sublist
sublists = [l[x*n:x*n n] for x in range(0, 8)]
  • Related