简体   繁体   English

如果字符串在列表中,则打印列表的所有元素?

[英]Printing all elements of list if string is in list?

So, I'm trying to make a search function which will print out all of the instances in a 2D list if the searched string is present in the list. 因此,我尝试制作一个搜索功能,如果搜索到的字符串存在于列表中,则该功能将打印出二维列表中的所有实例。 So if the user searches for a term which is in the list, the program will return all the inner lists which have that term. 因此,如果用户搜索列表中的术语,则程序将返回所有包含该术语的内部列表。 This is what I have so far: 这是我到目前为止的内容:

def music_library(tracks):
while True:
    st_search = raw_input("Search tracks: ")
    for a in tracks if st_search == tracks:
        print a

However, this is giving me a syntax error. 但是,这给了我一个语法错误。 I also don't know if this is doing what I want it do to. 我也不知道这是否在做我想要做的事情。 If anyone knows what I'm trying to do, I would appreciate the help! 如果有人知道我要做什么,我将不胜感激!

You're close, I'd change it a little bit as follows. 您接近了,我将对其作如下更改。

def music_library(tracks):
    st_search = raw_input("Search tracks: ")
    for a in tracks:
        if st_search == a:
            print a

I'd write it like this 我会这样写

def find_track(albums, track):
    return [album for album in albums if track in album]

I have it tested in the interpreter, see if it is what you want 我在解释器中测试过,看看是否是您想要的

In [3]: albums = [['as','def','ded'], ['red','def','pil'],['ret','tre','yui']]

In [4]: def find_track(albums,track):
   ...:     return [album for album in albums if track in album]
   ...: 

In [5]: find_track(albums,'def')
Out[5]: [['as', 'def', 'ded'], ['red', 'def', 'pil']]

In [6]: find_track(albums,raw_input('Track? '))
Track? ded
Out[6]: [['as', 'def', 'ded']]

In [7]: 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM