python列表中元素值进行比较,Python:将列表中的元素相互比较

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

Here is my list:

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.

For example.

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.

How can I go about doing this?

解决方案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)

Output

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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值