Grasshoperist
Grasshoperist

Reputation: 25

split list to sublists according to value

begginer here. I have following lists (curves and length of curves):

crvs = [crv, crv, crv, crv, crv, crv, crv, crv, crv]
crvsLen = [18, 18, 18, 12, 12, 12, 12, 18, 12]

I need to create sub lists? or 2d arrays? of [crvs] according their lengths something as following (but actual [crvs]not their [crvsLen]):

[[18, 18, 18, 18]
[12, 12, 12, 12, 12]]

I was able to find count of unique values in list and their indexes via this:

listOfUniqueLenghts = list(dict.fromkeys(crvsLen))
listOfUniqueLenghts = [12, 18]
indices = [i for i, x in enumerate(crvsLen) if x == listOfUniqueLenghts[0]]

which returns following indexes of [crvs] with length 12 for instance:

indices = [3, 4, 5, 6, 8]

How can I store [crvs] in 2d array or complex list and access them separately according to their length given any number of unique crvsLen and their amount? I can use only stock libraries.

Thanks, Dan.

Upvotes: 1

Views: 64

Answers (2)

Jay Mody
Jay Mody

Reputation: 4033

Best way to achieve what you want would be to use a dictionary with list values:

d = collections.defaultdict(list)
for crv in crvs:
    d[len(crv)].append(crv)

Now, you have a dictionary where the keys are unique lengths, and the values are the list of crvs of that length.

Upvotes: 0

Mark
Mark

Reputation: 92440

It's probably easiest to make a dictionary keyed to length. Once you have that, you should be able to get anything else you need.

crvs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
crvsLen = [18, 18, 18, 12, 12, 12, 12, 18, 12]

d = {}

for length, value in zip(crvsLen, crvs):
    d.setdefault(length, []).append(value)

d
# {18: ['a', 'b', 'c', 'h'], 12: ['d', 'e', 'f', 'g', 'i']}

# all 18s:
d[18]
#['a', 'b', 'c', 'h']

# list of lists:
list(d.values())
# [['a', 'b', 'c', 'h'], ['d', 'e', 'f', 'g', 'i']]

Upvotes: 3

Related Questions