How to get the unique values from this type of data [(6, 7), (7, 7), (7, 7), (7, 6), (6, 7)] and filter it in separate column

Input data:

[('6', '7'), ('7', '7'), ('7', '7'), ('7', '6'), ('6', '7')] 

Desired output:

unique = [('6', '7')]
not_unique =  [('7', '7'), ('7', '7'), ('7', '6')]

This is what I have tried so far:

import collections
mylist = content.Pairs
mylist2 = []
for thing in mylist:
    thing = tuple(thing)
    mylist2.append(thing)
    set(mylist2)

input_list = set(mylist2)
elements_count = collections.Counter(input_list)
content['unique'] = [element for element in input_list if elements_count[element] == 1]
content['not_unique'] = [element for element in input_list if elements_count[element] > 1]

But it gives me this error

Error : jupyter hangsup

1 answer

  • answered 2020-01-28 15:07 Savage Henry

    Given your list: input_list = [('6', '7'), ('7', '7'), ('7', '7'), ('7', '6'), ('6', '7')]

    Without having to import any other packages, you could do this:

    1. Convert list of tuples into a list of strings:

    string_list = [item for entry in input_list for item in entry]

    1. Get the unique values from that list:

    unique_items = set(string_list)

    1. Put the resulting dict into whatever you would like. To get back your specific format of a list of tuples:

    unique_list = list(tuple(unique_items)) gives you:

    [('6', '7')]

    1. To get your requested non_unique_list, make/keep the unique items a tuple, so you can do:

    unique_tuple = tuple(unique_list) non_unique_list = [item for item in input_list if item != unique_tuple]

    [('7', '7'), ('7', '7'), ('7', '6')]