Other way to retrieve index of duplicate elements


(Gethze) #1

I have a list with elements (sometimes letters, sometimes coordinates). I want to list the index of the duplicate elements. The “sort duplicate values” component does not work for this case because I need to retrieve the duplicate element index or null for each element in the same order that the original list is.

In other words, I would like the list to look like the attached image (null values are important to me).

I think it could be solved with a ghpyton script, but I’m starting to learn it.


in GH, try create set, then cull duplicates, then set difference between original and culled; this will give you a list of nulls

(Matt Gaydon) #3

Does this work as you are wanting?


(Gethze) #4

Thanks Marks
The idea is good, I’m trying to make it work

(Gethze) #5

Thanks Matt :slightly_smiling_face:, but it´s not what I’m looking :frowning_face:
Maybe I didn’t explain it clearly. The items of my list are sometimes letters and sometimes coordinates, but not both in the same list (sorry for the confusion). Some items in the list are duplicated. In the example I posted, the 0 index has the element C and it’s the same element stored in the 4 index. In the result I want to have the 0 index storing the number 4 that is the index of the duplicated element, but also I want to have the 4 index storing the number 0. The elements that aren’t duplicated in the list should appear like “null”

(qythium) #6

Yep, this is a good use for a few simple lines of scripting:

mapping = [None] * len(x)
for i, elem in enumerate(x):
        j = x.index(elem, i + 1)  # look ahead
        mapping[i] = j
        mapping[j] = i
    except ValueError: # no match found
a = mapping

note: this assumes that each element is duplicated at most twice


Didn’t test it for another longer list thought…

Retrieve Duplicated index_re.gh (8.1 KB)

(Radovan Grmusa) #8

Generally,there may more than one duplicate item in the list…

With two lines of C# code you can do it:

private void RunScript(List x, int index, ref object A)
var groupByOneX = x.Select((o, i) => new { o, i }).ToLookup(a => a.o, a => a.i)[x[index]].ToList();
A = groupByOneX;

Retrieve_Duplicate_Indexes_rg1.gh (8.1 KB)

(Gethze) #9

It works perfect, thank you! :grinning:

(Gethze) #10

Thanks, Qythium. It looks like an elegant solution :slightly_smiling_face: but I don’t know why it’s not working for me, did I omitted something?

(qythium) #11

Ah, I forgot to mention that x should be set to List Access (via right click menu) - the default behaviour runs the component N times for each value in the input.

Here’s the file: Retrieve Duplicated index.gh (4.2 KB)

(Gethze) #12

Thanks for your help, @qythium. I really appreciate it :grinning: