【问题标题】:Python: Comparing elements in a list and printing elements with the biggest match countPython:比较列表中的元素并打印具有最大匹配数的元素
【发布时间】:2017-01-09 03:02:48
【问题描述】:

我刚开始学习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.

任何帮助将不胜感激。 谢谢。

【问题讨论】:

标签: python python-2.7 list


【解决方案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']]

【讨论】:

  • 谢谢,它非常简单地解决了我的问题,但我有问题。例如,我如何打印 3 个答案中的 2 个?如何更改打印方式,例如在另一个答案下打印一个答案?
  • @user7375796 你可以得到一个slice的列表。如果您想获取前 n 个元素,只需执行 l[:n]。例如,前 2 个元素:l[:2],在本例中为 [['red', 'blue', 'black'], ['red', 'blue', ' white']
猜你喜欢
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
相关资源
最近更新 更多