Python:将列表中的元素相互比较 [英] Python: Compare elements in a list to each other

查看:468
本文介绍了Python:将列表中的元素相互比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在寻找一种将列表中的元素从左到右进行比较的方法.

I'm currently looking for a way to compare elements of a list to one another going from left to right.

这是我的清单:

mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]]

我需要将第一个元素与所有其他元素进行比较,并检查是否有任何值匹配,第二个和第三个元素是否相同,依此类推,直到到达列表末尾.如果有匹配项,我需要将其打印出来.我需要打印出具有匹配的值和与之匹配的索引.

I need to compare the first element to all others and check if any of the values match, same thing for the second and third element and so on until it reaches the end of the list. If there is a match, I need to print it out. I need to print out the value that has match and the index that it matched at.

例如.

index 0 matched with index 1 for value 15.
index 2 matched with index 5 for value 19
index 2 matched with index 6 for value 19
index 2 matched with index 6 for value 20
index 5 matched with index 6 for value 19.

我该怎么做?

推荐答案

mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]]
my_set_list = [set(item) for item in mylist]
for i1, item in enumerate(my_set_list):
    for i2 in xrange(i1 + 1, len(my_set_list)):
        for val in (item & my_set_list[i2]):
            print "Index {} matched with index {} for value {}".format(i1,i2,val)

输出

Index 0 matched with index 1 for value 15.
Index 2 matched with index 5 for value 19.
Index 2 matched with index 6 for value 19.
Index 2 matched with index 6 for value 20.
Index 5 matched with index 6 for value 19.

这篇关于Python:将列表中的元素相互比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆