-3

If I have a list:

a=[6,3,2,5,1,4]

and a specific size likes 3, so number 1~2 will tagged 1, 3~4 tagged 2, 5~6 tagged 3, likes list b:

b=[3,2,1,3,1,2]

How can I efficient to do this? Note that list could be floating number

Sorry for unclear description, Update with more complex example:

a=[2.5,1.4,1.6,2.1,1.5,0.7]

output will be :

b=[3,1,2,3,2,1]
chuzz
  • 55
  • 1
  • 8
  • Does this answer your question? [Split list into smaller lists (split in half)](https://stackoverflow.com/questions/752308/split-list-into-smaller-lists-split-in-half) – iacob Mar 24 '21 at 15:40

3 Answers3

1

This is what you need :

import math
a=[6,3,2,5,1,4]
size = 3
b = list(a)
b.sort()
for i in range(len(a)) :
    w = len(b)/size                             #1
    a[i] = math.ceil((b.index(a[i]) + 1)/(w))   #2

print(a)

1: we're getting the length of each chunk

2: we're getting in which chunk the number is present in our sorted list and replacing it with the number of the chunk in the original list

marc
  • 914
  • 6
  • 18
1

You can achieve this by first ordering the list, and splitting it into chunks of the desired size:

a=[6,3,2,5,1,4]
n = 3

a_ord = sorted(a)

def split_list(alist, wanted_parts=1):
    length = len(alist)
    return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] 
             for i in range(wanted_parts) ]

x = split_list(a_ord,n)

And then crating a dictionary using these chunks as the bins:

d = {j:x.index(i)+1 for i in x for j in i}

print(d)
>>> {1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 3}

And then mapping the values using the dictionary:

b = [d[key] for key in a]

print(b)
>>> [3, 2, 1, 3, 1, 2]
iacob
  • 20,084
  • 6
  • 92
  • 119
-1
sample_dict = {
        1:1,
        2:1,
        3:2,
        4:2,
        5:3,
        6:3
    }

for k in a:
    out_arr.append(sample_dict[k])
    
print (out_arr)
iacob
  • 20,084
  • 6
  • 92
  • 119
madmatrix
  • 205
  • 1
  • 4
  • 12
  • 1
    This is a hard-coded dictionary and will not work with a different size of array or bin size. – iacob Jul 25 '18 at 07:40