I'd like to break up the list elements into four pieces and approach them

Asked 2 years ago, Updated 2 years ago, 110 views

You want to split four elements into a list that stores only integers. Right now, it's just i+1, i+2,... Is there any other way?

It hasn't been long since I came over from C, so I keep coming up with the habit I did in C even though I make the Python code.

for i in xrange(0, len(ints), 4):
    # # dummy op for example code
    foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]

//or
while ints:
    foo += ints[0] * ints[1] + ints[2] * ints[3]
    ints[0:4] = []

list loops python optimization chunk

2022-09-22 11:14

1 Answers

The easiest and fastest function to divide itable by a uniform chunk is

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))

If you are using Python3, please change xrange to range

Examples of use are

text = "I am a very, very helpful text"

for group in chunker(text, 7):
   print repr(group),
# # 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt'

print '|'.join(chunker(text, 10))
# # I am a ver|y, very he|lpful text

animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish']

for group in chunker(animals, 3):
    print group
# # ['cat', 'dog', 'rabbit']
# # ['duck', 'bird', 'cow']
# # ['gnu', 'fish']

Another code for dividing the list by chunk is I want to divide the Python list into uniform sizes


2022-09-22 11:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.