2017-01-08 54 views
2

我剛開始學習python。Python:比較列表中的元素並打印最大匹配計數的元素

我試圖比較列表中的元素。比如我有一個列表:

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

現在,我怎麼可以比較元素0:['red','blue','black']與列表中的元素的其餘部分,打印與比賽的最大數量的元素,如最匹配的元素是['red', 'blue', ' white']接下來['red', 'pink']

更新:

在這一點上,我設法做這樣的事情:

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)] 

輸出:

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

我已經找到了解決辦法: Python: Compare elements in a list to each other

任何幫助將不勝感激。 謝謝。

+1

你能告訴你有什麼到目前爲止已經試過?解釋你的實施的哪一部分給你帶來困難。 – idjaw

+0

嘗試使用計數器 - https://docs.python.org/2/library/collections.html#counter-objects –

+0

或者['set'](https://docs.python.org/2/library/stdtypes的.html#集類型,設置frozenset)。 – mkrieger1

回答

1

您可以按組交叉的長列表:

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']] 
+0

謝謝,它對我的​​probelm非常簡單的解決方案,但我有問題。 我如何打印例如ony 2 3答案? 我該如何改變打印方式,例如在另一個打印下打印一個答案? – user7375796

+0

@ user7375796您可以獲得列表的[slice](http://stackoverflow.com/q/509211/4229825)。如果你想獲得前n個元素,只需要'l [:n]'。例如,在這種情況下,前兩個元素是'[['2'],它們是[[''紅','藍','黑'],['紅','藍','白']] 。 – 0x1337

+0

是的!即時通訊如此愚蠢,謝謝! – user7375796