Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

Search for Multiple Sublists of Same List in 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...