搜索终端输入列表并将匹配项存储到新lis

2024-10-02 18:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

def findSongs(jukeBox):
    search = input('Enter a word you want to search in the dataset:')
    cnt=0
    for artist in jukeBox:
        artist = artist.strip().split(',')
        if search.lower() in ''.join(artist).lower():
            cnt+=1
    print('\n\nFound' , cnt, 'matches:\n------------------------\n')
    for artist in jukeBox:
        artist = artist.strip().split(',')
        if search.lower() in ''.join(artist).lower():
            printSong(artist[0],artist[1],artist[2],artist[3])

我有代码,将搜索终端输入列表,我想存储匹配的数据到一个列表,这样我就不必搜索一次,以获得一个计数和搜索再次打印。你知道吗


Tags: in列表forinputsearchifartistdef
2条回答

只需在列表中存储匹配的艺术家:

def findSongs(jukeBox):
    search = input("Enter a word you want to search in the dataset:")
    matching_artists = []
    for artist in jukeBox:
        artist = artist.strip().split(",")
        if search.lower() in "".join(artist).lower():
            matching_artists.append(artist)
    print("\n\nFound", len(matching_artists), "matches:\n            \n")
    for artist in matching_artists:
        print(artist[0], artist[1], artist[2], artist[3])

如果您试图实现Memoization,那么这是跟踪历史结果以减少计算并加快程序速度的好方法。下面是关于如何开始的示例代码

history = dict()

def findSongs(jukeBox):
    search = input('Enter a word you want to search in the dataset:')
    cnt=0
    if search in history.keys():
        # The search term exists, to access the previous result -
        # - from the dict: history[search]
    else:
        for artist in jukeBox:
            artist = artist.strip().split(',')
            if search.lower() in ''.join(artist).lower():
                cnt+=1
        print('\n\nFound' , cnt, 'matches:\n            \n')
        for artist in jukeBox:
            artist = artist.strip().split(',')
            if search.lower() in ''.join(artist).lower():
                printSong(artist[0],artist[1],artist[2],artist[3])
                # Makre sure to update the dictionary here 
                # history[search] = [results list]
                # or history[search] = history[search].append(newElement)

相关问题 更多 >