Python:比较一个列表中的元素,并打印出匹配度最大的元素

2024-04-26 05:49:34 发布

您现在位置: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。你知道吗

任何帮助都将不胜感激。 谢谢。你知道吗


Tags: in元素列表forindexwithbluered
1条回答
网友
1楼 · 发布于 2024-04-26 05:49:34

可以按交叉点集的长度对列表进行排序:

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

相关问题 更多 >