in在python中的用法,在Python中使用'in'测试另一个子列表的一部分

Newbie here trying to search for part of one sublist within another sublist.

list_1 = [[1, 2, 9], [4, 5, 8]]

list_2 = [[1, 2, 3], [4, 5, 6], [1, 2, 5]]

for item in list_1:

for otherItem in list_2:

item[0:2] in otherItem[0:2]

I was hoping this would return

True

False

True

False

True

False

But instead I get false for every iteration.

In a nutshell:

list_1[0][0:2] == list_2[0][0:2] #this returns true

list_1[0][0:2] in list_2[0][0:2] #this returns false

I guess I don't understand how in works. Can anyone school me here?

解决方案

in looks to see if one sublist is an element (not sublist) of another list:

[1,2] in [[1,2],[3,4]]

would be True.

[1,2] in [1,2,3]

would be False as would:

[1,2] in [1,2]

However:

[1,2] == [1,2]

would be True. Depending on what you're actually trying to do, set objects might be useful.

a = [1,2]

b = [1,2,3]

c = [3,2,1]

d = [1,1,1]

e = set(a)

len(e.intersection(b)) == len(a) #True

len(e.intersection(c)) == len(a) #True -- Order of elements does not matter

len(e.intersection(d)) == len(a) #False

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值