Home > database >  List - breaking out a list of tuples into specific set size, but the size of the sets doesn't h
List - breaking out a list of tuples into specific set size, but the size of the sets doesn't h

Time:06-15

I noticed alot of the questions similarly formatted but it seems they specify how many elements in each chunk rather the the number of sets the list is split into.

I have about 3k tuples in a list, everyday it increases by about 10, this is a sample:

my_list = [(12,383),(44,23428),(858,12),(1231,59540),(3242,569324),(11,58435),(32, 1231),(13123,34324),(441, 1485),(12111,3923)]

I want to break out the list of tuples in 3 groups so there would be 3 , 3, 4 since there are 10 in the my_list example

This doesn't work because it breaks out the list of tuples to have 3 tuples in each group, but I want to make sure there are groups

final = [my_list[i * 3:(i   1) * 3] for i in range((len(my_list)   3 - 1) // 3 )]
print (final)

The output preferable is like below, 3 sets:

[(12, 383), (44, 23428), (858, 12)]
[(1231, 59540), (3242, 569324), (11, 58435)]
[(32, 1231), (13123, 34324), (441, 1485), (12111, 3923)]

CodePudding user response:

If I understand correctly, using a generator in conjunction with itertools.islice would be most useful.

def grouper(lst, partition):
    it = iter(lst)
    for part in partition:
        yield list(islice(it, part))

for group in grouper(my_list, partition=(3, 3, 4)):
    print(group)

# [(12, 383), (44, 23428), (858, 12)]
# [(1231, 59540), (3242, 569324), (11, 58435)]
# [(32, 1231), (13123, 34324), (441, 1485), (12111, 3923)]

CodePudding user response:

Transliterating your requirements into code comes out like this:

NUM_GROUPS = 3
my_list = [(12,383),(44,23428),(858,12),(1231,59540),(3242,569324),(11,58435),(32, 1231),(13123,34324),(441, 1485),(12111,3923)]

len_mylist = len(my_list)

new_size = len_mylist // NUM_GROUPS

short_count = new_size * NUM_GROUPS
excess = len_mylist-short_count

final = [my_list[i*NUM_GROUPS:(i 1)*NUM_GROUPS] for i in range(new_size)]
if excess:
    final[-1].extend(my_list[-excess:])
  • Related