SoFunction
Updated on 2024-11-16

Python split list list method use (average n equal parts split into)

1. Introduction

In daily development, sometimes you need to split a large list into a fixed list of small, and then related processing. Here to see the details of the split method:

2. Methodology

2.1 Splitting large lists into small lists of 1 element

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> r = [[x] for x in a]
>>> r
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]

2.2 Splitting large lists into small lists of 3 elements

2.2.1 General methods

In [17]: lst
Out[18]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [18]: for i in range(0,len(lst),3): print(lst[i:i+3])
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]

2.2.2 Improvement of methods

Improvement: use a list derivation where the results are all put into one list.

In [35]: lst
Out[35]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [36]: b = [lst[i:i+3] for i in range(0,len(lst),3)]
In [37]: b
Out[37]: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

2.2.3 The lambda method

In [10]: f = lambda a:map(lambda b:a[b:b+3],range(0,len(a),3))
In [11]: lst
Out[11]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [12]: f(lst)
Out[12]: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

2.3 Average n equal parts

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l = len(a)    # length of a
>>> l
10
>>> n = 5    # Average 5 equal parts
>>> step = int(l/n)    # Steps
>>> step
2
>>> b = [a[i:i+step] for i in range(0, l, step)]
>>> b
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

3. Reference

【1】https:///article/

to this article on the use of Python split list list method (average n equal parts split into) of the article is introduced to this, more related Python split list list content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!