Home > Blockchain >  Need to split an array based on another array containing size Python
Need to split an array based on another array containing size Python

Time:06-28

I have 2 arrays - one containing data and the other containing a size that the data needs to be broken into:

data = [{"a":1,"b":2,"c":3}]
size = [1,2]

I would like the output to look like this:

data = [{"a":1} , {"b":2,"c":3}]

I'm basically trying to do this without doing a bunch of for loops but I'm still new to python. Anything more performant than looping through?

CodePudding user response:

You can shorten the code by using itertools.islice, list comprehension and dictionary comprehension. Note that these are versions of loops, so while the code is shorter than that using for loops, it still has a bunch of loops, essentially. But there is no way to avoid loops altogether in one form or another:

from itertools import islice

data = [{"a":1,"b":2,"c":3}]
size = [1,2]

data_dct = data[0]
data_keys = list(data_dct.keys())
it = iter(data_keys)

sliced_data_keys = [list(islice(it, 0, s)) for s in size]

sliced_data = []
for lst in sliced_data_keys:
    sliced_data.append({k: data_dct[k] for k in lst})

print(sliced_data)
# [{'a': 1}, {'b': 2, 'c': 3}]

CodePudding user response:

Notwithstanding OP's apparent aversion to for loops, here's an example that does use for loops but does not rely on any additional module imports.

data = [{"a": 1, "b": 2, "c": 3}]

size = [1, 2]

assert len(data[0]) == sum(size) # otherwise this won't work

new_data = []

items = iter(data[0].items())

for s in size:
    new_data.append({})
    for _ in range(s):
        k, v = next(items)
        new_data[-1][k] = v

print(new_data)

Output:

[{'a': 1}, {'b': 2, 'c': 3}]
  • Related