2

It's really childish to ask this question but really want an optimal solution for this. I have an array of string

("a1,a2", "a3,a4", "a2,a1", "a5,a3")

and I want to Display

("a1,a2", "a3,a4", "a5,a3")

i.e. the first string is in, its duplicates are omitted.

Note: the order of the elements must be preserved

2

2 Answers 2

3

This is one approach.

Ex:

data =  ("a1,a2","a3,a4","a2,a1","a5,a3") 
seen = set()
result = []
for i in data:
    if ",".join(sorted(i.split(","))) not in seen:
        result.append(i)
        seen.add(i) 
print(result)

Output:

['a1,a2', 'a3,a4', 'a5,a3']
Sign up to request clarification or add additional context in comments.

3 Comments

the inner list (the one inside set) is unnecessary
I forgot to add about the "order" in the question. Actually order is required. Thank you for the answer. will try the answer.
@SharathNayak. Updated snippet
0

your data is in a variable called "data".

new_data = []
for example in data:
    example2 = str(example.split(",")[1] + "," + example.split(",")[0])
    if example in new_data or example2 in new_data:
        continue 
    else:
        new_data.append(example) 
print(new_data) 

If you want to store them in your original list, run this script.

data.clear()
data = new_data.copy()

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.