【发布时间】: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.
任何帮助将不胜感激。 谢谢。
【问题讨论】:
-
你能展示一下你到目前为止所做的尝试吗?解释你的实施中哪一部分给你带来了困难。
-
或者更确切地说是
set。 -
只匹配内容还是位置?
-
仅在内容中
标签: python python-2.7 list