Split a Python List into Other "Sublists" I.E Smaller Lists

Split a python list into other sublists i.e smaller lists

I'd say

chunks = [data[x:x+100] for x in range(0, len(data), 100)]

If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange(), changing the above code to:

chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

Split list into smaller lists (split in half)

A = [1,2,3,4,5,6]
B = A[:len(A)//2]
C = A[len(A)//2:]

If you want a function:

def split_list(a_list):
half = len(a_list)//2
return a_list[:half], a_list[half:]

A = [1,2,3,4,5,6]
B, C = split_list(A)

Divide a list into smaller lists

So, I hardly tried to make it in one line. Here is what I ended up with

import math

nb_classes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
N = 3

lists = [nb_classes[math.ceil(i): math.ceil(i + len(nb_classes) / N)] for i in (len(nb_classes) / N * j for j in range(N))]

print(lists) # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

But this may be a little bit complicated, you just need to ceil your indexes

How do I split a list into equally-sized chunks?

Here's a generator that yields evenly-sized chunks:

def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[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, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]

For Python 2, using xrange instead of range:

def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in xrange(0, len(lst), n):
yield lst[i:i + n]

Below is a list comprehension one-liner. The method above is preferable, though, since using named functions makes code easier to understand. For Python 3:

[lst[i:i + n] for i in range(0, len(lst), n)]

For Python 2:

[lst[i:i + n] for i in xrange(0, len(lst), n)]

split a list using list to get smaller lists

  1. You can compute the indexes of each title:

    indexes = list(map(x.index, titles))
    # or indexes = [x.index(title) for title in titles]
  2. Then zip indexes with indexes[1:] this will make pairs of each index with the next one:

    z = zip(indexes, indexes[1:] + [None])
    print(list(z)) # [(0, 4), (4, 8), (8, 9), (9, None)]
  3. Then use it to split:

    • To get the list of sublists:

      resultlist = [x[fr:to] for fr, to in zip(indexes, indexes[1:] + [None])]
      # [['a', 3, 4, 2], ['c', 'b', 'b1', 2], ['g'], ['final', 'value']]
    • To get the dict:

      resultdict = {x[fr]: x[fr + 1:to] for fr, to in zip(indexes, indexes[1:] + [None])}
      # {'a': [3, 4, 2], 'c': ['b', 'b1', 2], 'g': [], 'final': ['value']}

Python: Split a list into multiple lists based on a subset of elements

Consider using one of many helpful tools from a library, i.e. more_itertools.split_at:

Given

import more_itertools as mit

lst = [
"abcd 1233", "cdgfh3738", "hryg21", "**L**",
"gdyrhr657", "abc31637", "**R**",
"7473hrtfgf"
]

Code

result = list(mit.split_at(lst, pred=lambda x: set(x) & {"L", "R"}))

Demo

sublist_1, sublist_2, sublist_3 = result

sublist_1
# ['abcd 1233', 'cdgfh3738', 'hryg21']
sublist_2
# ['gdyrhr657', 'abc31637']
sublist_3
# ['7473hrtfgf']

Details

The more_itertools.split_at function splits an iterable at positions that meet a special condition. The conditional function (predicate) happens to be a lambda function, which is equivalent to and substitutable with the following regular function:

def pred(x):
a = set(x)
b = {"L", "R"}
return a.intersection(b)

Whenever characters of string x intersect with L or R, the predicate returns True, and the split occurs at that position.

Install this package at the commandline via > pip install more_itertools.

Split a list of dictionaries into multiple lists of dictionaries in python

You can try this:

l = [{'system_name': 'W1PVTL1098', 'fdc_inv_sa_team': 'X3Virtualization'},
{'system_name': 'W1PVTL1100', 'fdc_inv_sa_team': 'X3Virtualization'},
{'system_name': 'r3bvap1154', 'fdc_inv_sa_team': 'X2Linux_NSS'},
{'system_name': 'r1qvap1281', 'fdc_inv_sa_team': 'X2Linux_NSS'},
{'system_name': 'R3QVAP1123', 'fdc_inv_sa_team': 'X2Linux_GBS'},
{'system_name': 'W3BVAP1294', 'fdc_inv_sa_team': 'X2Windows_NSS'}]

n = 3
n1 = len(l)//n
new = [l[i:i+n1] for i in range(0, len(l), n1)]
print new

This code now creates a list that contains the data broken into n sublists.

Output:

[[{'system_name': 'W1PVTL1098', 'fdc_inv_sa_team': 'X3Virtualization'}, {'system_name': 'W1PVTL1100', 'fdc_inv_sa_team': 'X3Virtualization'}], [{'system_name': 'r3bvap1154', 'fdc_inv_sa_team': 'X2Linux_NSS'}, {'system_name': 'r1qvap1281', 'fdc_inv_sa_team': 'X2Linux_NSS'}], [{'system_name': 'R3QVAP1123', 'fdc_inv_sa_team': 'X2Linux_GBS'}, {'system_name': 'W3BVAP1294', 'fdc_inv_sa_team': 'X2Windows_NSS'}]]

Split a list into sub-lists based on index ranges

Note that you can use a variable in a slice:

l = ['a',' b',' c',' d',' e']
c_index = l.index("c")
l2 = l[:c_index]

This would put the first two entries of l in l2

How to split one list in a list of x list with python?

You may try like this:

EDIT2:-

i,j,x=len(seq),0,[]

for k in range(m):

a, j = j, j + (i+k)//m

x.append(seq[a:j])

return x

Call like

seq = range(11), m=3

Result

result : [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]


def chunks(l, n):
return [l[i:i + n] for i in range(0, len(l), n)]

EDIT1:-

>>> x = [1,2,3,4,5,6,7,8,9]
>>> zip(*[iter(x)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]


Related Topics



Leave a reply



Submit