Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

string - Python: Find a name in a list of lists

So, I've to search for a name in a list and the code has to give me all the contacts with that name. Ex: My code is:

def find_contacts(contacts = [['Bruno Jr', '@brunojr'], ['Brunosvaldo Kean', 'brunosvaldo_kean']], name = 'Bruno'):
    for list in contacts:
        if name in list:
            print(name)

The output should be [['Bruno Jr'],[Brunosvaldo Kean]] but instead I get nothing, I really don't know why Python won't give me the names. Someone please help me understand the error.

question from:https://stackoverflow.com/questions/66052501/python-find-a-name-in-a-list-of-lists

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

1 Answer

0 votes
by (71.8m points)

If you want to find items that contain name, try this:

def find_contacts(contacts = [['Bruno Jr', '@brunojr'], ['Brunosvaldo Kean', 'brunosvaldo_kean']], name = 'Bruno'):
  for list in contacts:
    for item in list:
      if name in item:
        print(name)

find_contacts()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...