python列表包含子列表_在Python中搜索相同列表的多个子列表

I need Python to search all the sublists of a given list, but this does not work when I'm searching for an element contained in only one of them. For example, this is my code:

data = [[4,5],[4,7]]

search = 4

for sublist in data:

if search in sublist:

print("there", sublist)

else:

print("not there")

print(data)

and this works very well if my search is contained in all of the sublists of the lists. However, if my search is, for instance, 5, then I get:

there [4,5] #I only want this part.

not there # I don't want the rest.

[[4, 5], [4, 7]]

EDIT:

Basically, I need Python to list all the lists the search is contained in, but if the search is only contained in one sublist, I only want the print("there", sublist). In other words, I only want Python to recognize the places the search is in, and not output where it is not, so no print("not there") print(data).

解决方案

Try using a boolean tag. For example:

data = [[4,5],[4,7]]

search = 5

found = false

for sublist in data:

if search in sublist:

print("there", sublist)

found = true

if found == false:

print("not there")

print(data)

This way the print data is outside the for loop and won't be printed each time a sublist is found that does not contain search.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值