Home > OS >  Change Data Structure of an array (new ID and replace Duplicates in loop)
Change Data Structure of an array (new ID and replace Duplicates in loop)

Time:11-16

I'm new in the "python game", so maybe the following question is for some of you very easy to answer:

I have an array like this:

store=([9,4,5],[9,4,1],[1,2,3],[9,4,1],[3,7,5],[2,4,1]) 

I want to "loop" the array and creat a new structure:

store_new=([0,1,2],[0,1,3],[3,4,5],[0,1,3],[5,6,2],[4,1,3]) 

The first value starts with 0, the second is 1 and so on. If there is a duplicate it should take the same new value as before. For example for "9"(old) to "0"(new)....and for the next "9"(old) again to "0" (new). Is there a nice way to handle this problem?

I tried something with “enumerate” in a “for loop”...but this don't really work.

CodePudding user response:

You can use itertools.count and dict.setdefault in a list comprehension:

store=([9,4,5],[9,4,1],[1,2,3],[9,4,1],[3,7,5],[2,4,1])

from itertools import count

d = {}
c = count()
out = tuple([d[x] if x in d else d.setdefault(x, next(c)) for x in l]
            for l in store)

Output:

([0, 1, 2], [0, 1, 3], [3, 4, 5], [0, 1, 3], [5, 6, 2], [4, 1, 3])

With a classical python loop:

out = []
d = {}
max_val = 0
for l in store:
    out.append([])
    for x in l:
        if x in d:
            out[-1].append(d[x])
        else:
            d[x] = max_val
            out[-1].append(max_val)
            max_val  = 1

out = tuple(out)
  • Related