2

I have just started learning python.

I'm trying to compare elements in the list. For example I have a list:

list = [['red', 'blue', 'black'], ['red', 'blue', ' white'], ['red', 'pink']]

Now, how can I compare element 0: ['red','blue','black'] with the rest of elements in the list and print those elements with the biggest count of matches, like the most matching element is ['red', 'blue', ' white'] next ['red', 'pink']

Update:

At this point I managed to do something like this:

mylist = [set(item) for item in list]
for i, item in enumerate(mylist):
    for i1 in xrange(i + 1, len(mylist)):
        for val in (item & mylist[i1]):
            print "Index {} matched with index {} for value
{}".format(i,i1,val)
            if i == 0:
                print list[(i1)]

Output:

Index 0 matched with index 1 for value "Red"
['red', 'blue', ' white']
Index 0 matched with index 1 for value "Blue"
['red', 'blue', ' white']
...

I have found a solution: Python: Compare elements in a list to each other.

Any help would be much appreciated. Thanks.

Community
  • 1
  • 1
user7375796
  • 45
  • 1
  • 1
  • 5

1 Answers1

1

You can sort a list by a length of sets of intersections:

key = ['red', 'blue', 'black']
l = [['red', 'pink'], ['red', 'blue', ' white'], ['red', 'blue', 'black']]
sorted_by_matching = sorted(l, key=lambda x: -len(set(x) & set(key)))

print(sorted_by_matching)
>> [['red', 'blue', 'black'], ['red', 'blue', ' white'], ['red', 'pink']]
0x1337
  • 1,074
  • 1
  • 14
  • 33
  • Thanks, its very simple solution to my probelm, but i have questions. How can i print for example ony 2 out of 3 answers? How can i change the way that is printed, for example printed one answer under another? – user7375796 Jan 08 '17 at 19:13
  • @user7375796 You can get a [slice](http://stackoverflow.com/q/509211/4229825) of the list. If you want to get first n elements, just do `l[:n]`. For example, first 2 element: `l[:2]`, which are `[['red', 'blue', 'black'], ['red', 'blue', ' white']` in this case. – 0x1337 Jan 08 '17 at 19:17