我刚开始学习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 .
任何帮助将不胜感激。 谢谢。
请您参考如下方法:
您可以按交叉集的长度对列表进行排序:
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']]
