'Return all labels that contain repeated elements of array
I have data that looks like this in python: Notice that the first and last two elements have repeats of that array.
for _, m in enumerate(array)
print(_,m)
#Output:
1 [2,3]
2 [8,8]
2 [9,7]
3 [1,1]
3 [2,3]
4 [8,8]
I want a function that outputs the labels only if there are repeats of that array. Something like this:
[2,3]: 1,3
[8,8]: 2,4
The code I want should be something like this?
for _, m in enumerate(array):
if m repeats:
print(m, _.all())
Solution 1:[1]
hope this will answer to your needs, still try to follow the advice about MRE next time
lets start defining a simple function to list all positions of an element into a list
the next step would be to actually print an element one time only if it is contained 2 or more times into the "array". this is achievable using a list to keep the items already checked (found)
def find_positions(n_array, to_find):
return [i for i in [i for i in range(len(n_array))] if to_find == n_array[i]]
if __name__ == "__main__":
array = [[2,3],[8,8],[9,7],[1,1],[2,3],[8,8]]
found = []
for element in array:
if element not in found:
found.append(element)
position = find_positions(array, element)
if len(position)>1:
print(element,":",position)
this above is an example of an MRE of a solution ;)
output:
[2,3] : [0,4]
[8,8] : [1,5]
Note that the indexing of the positions starts with 0, a choice to be in line with python indexing ;)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrCont |
