-2

How to remove duplicates across the multi-dimensional array: example:

[
[125.25,129,128,129],
[124.25,127,130,131],
[126,126,125,124],
[126,124,130,124]
]

and I want, the output should be:

[
[125.25,129,128],
[124.25,127,130,131],
[126,125,124]
]
3
  • 2
    Possible duplicate of Remove Duplicates in two-dimensional array while maintaining sequence Commented Oct 22, 2018 at 17:50
  • No, I need each element of all arrays should be unique, no duplication of values across the array. Commented Oct 22, 2018 at 17:54
  • 1
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem individually. A good way to show this effort is to include a Minimal, complete, verifiable example. Check the intro tour you finished before posting, especially How to Ask. Commented Oct 22, 2018 at 17:55

3 Answers 3

1

Maybe not the shortest but something like this would work:

arrs = [
[125.25,129,128,129],
[124.25,127,130,131],
[126,126,125,124],
[126,124,130,124]
]

alreadyExisting = []
removedDuplicatesArr = []

for arr in arrs:
    newArr = []
    for i in arr:
        if i not in alreadyExisting:
            alreadyExisting.append(i)
            newArr.append(i)
    if newArr:
        removedDuplicatesArr.append(newArr)

print(removedDuplicatesArr)
Sign up to request clarification or add additional context in comments.

1 Comment

I'd make alreadyExisting a set to make the if i not in alreadyExisting check O(1).
0
yourlist = [
    [125.25,129,128,129],
    [124.25,127,130,131],
    [126,126,125,124],
    [126,124,130,124]
]
def seen(element, _cache=set()):
    result = element in _cache
    _cache.add(element)
    return result

filtered = ([x for x in sublist if not seen(x)] for sublist in yourlist)
filtered = [sublist for sublist in filtered if sublist] # filter out empty lists

1 Comment

Almost - what about empty lists? In his example, these are removed
0

Use set to eliminate the duplicates in sublists , then check if item of sublist exists in res if not append those values to a tmp list and then append that list to your res

res = []
lst = [set(i) for i in lst]

for i in lst:
    tmp = []
    for j in i:
        if not any(j in i for i in res):
            tmp.append(j)
    if tmp:
        res.append(sorted(tmp))

print(res)
# [[125.25, 128, 129], [124.25, 127, 130, 131], [124, 125, 126]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.