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

Pynchia
11.7k5 gold badges37 silver badges49 bronze badges
asked Sep 9, 2019 at 8:20
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']
answered Sep 9, 2019 at 8:23
3
  • the inner list (the one inside set) is unnecessary Commented Sep 9, 2019 at 8:28
  • I forgot to add about the "order" in the question. Actually order is required. Thank you for the answer. will try the answer. Commented Sep 9, 2019 at 8:28
  • @SharathNayak. Updated snippet Commented Sep 9, 2019 at 8:32
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()
answered Sep 9, 2019 at 8:37
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.