Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading