且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:将列表中的元素相互比较

更新时间:2023-02-05 14:12:33

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.