How to break a list into chunks of N

Configurare noua (How To)

Situatie

Method1:Using Yield

The yield keyword enables a function to comeback where it left off when it is called again

Backup

my_list = ['geeks', 'for', 'geeks', 'like',
           'geeky','nerdy', 'geek', 'love',
               'questions','words', 'life']
 
# Yield successive n-sized
# chunks from l.
def divide_chunks(l, n):
     
    # looping till length l
    for i in range(0, len(l), n): 
        yield l[i:i + n]
 
# How many elements each
# list should have
n = 5
 
x = list(divide_chunks(my_list, n))
print (x)

Output:

[['geeks', 'for', 'geeks', 'like', 'geeky'], 
 ['nerdy', 'geek', 'love', 'questions', 'words'], 
 ['life']]

Solutie

Method2: List comprehension
List comprehension is an elegant way to break a list in one line of code.

my_list = [1, 2, 3, 4, 5,
              6, 7, 8, 9]
 
# How many elements each
# list should have
n = 4
 
# using list comprehension
final = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] 
print (final)
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

Tip solutie

Permanent

Voteaza

(12 din 21 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?