所以,我正在尝试创建一个搜索功能,如果搜索到的字符串出现在列表中,它将打印出2D列表中的所有实例。因此,如果用户搜索列表中的术语,程序将返回具有该术语的所有内部列表。这就是我到目前为止所做的:
def music_library(tracks):
while True:
st_search = raw_input("Search tracks: ")
for a in tracks if st_search == tracks:
print a
但是,这给了我一个语法错误。我也不知道这是否正在做我想做的事情。如果有人知道我想要做什么,我会很感激帮助!
答案 0 :(得分:0)
您已经关闭,我会稍微改变一下。
def music_library(tracks):
st_search = raw_input("Search tracks: ")
for a in tracks:
if st_search == a:
print a
答案 1 :(得分:0)
我会这样写的
def find_track(albums, track):
return [album for album in albums if track in album]
我在解释器中测试了它,看看它是否是你想要的
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]: