2017-11-14 18 views
-1

なぜ空リストを取得するのか分かりませんが、この関数をテストします。誰でもこの問題を解決するのを助けてくれますか?キーワードが関連付けられたファイル名のリストを返します

def find_images_with_keyword(key_dict, keywords_list): 
'''(dict of {str: list of str}, list of str) -> list 
Given a keyword_dictionary and a list of keywords, 
return the list of filenames associated with the given keywords. 
The list of filenames should include all filenames having one or more 
of the specified keywords(ie, a filename may be associated with only one, 
not all of the keywords in the list). 
>>> find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png', '3.png']}, ['dog', 'animal']) 
    ['1.png', '2.png', '3.png'] 
''' 
new_list = [] 
for keyword in key_dict.items(): 
    for filename in keywords_list: 
     if keyword == filename: 
      new_list.append(filename) 
return new_list 
+0

現在のアイテムの名前として 'keyword'を使用する2つの' for'ループがあります。それらのうちの1つが 'filename'であると仮定していますか?そうでなければ、その変数が – UnholySheep

+0

であるはずなのかどうかは不明です。質問を整理できますか?入力は何ですか、期待される出力は何ですか? –

+0

'filename'は定義されていません。 –

答えて

0

この

def find_images_with_keyword(key_dict, keywords_list): 
    '''(dict of {str: list of str}, list of str) -> list 
    Given a keyword_dictionary and a list of keywords, 
    return the list of filenames associated with the given keywords. 
    The list of filenames should include all filenames having one or more 
    of the specified keywords(ie, a filename may be associated with only one, 
    not all of the keywords in the list). 
    >>> find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png', '3.png']}, ['dog', 'animal']) 
     ['1.png', '2.png', '3.png'] 
    ''' 

    found_imgs = set() 
    for keyword, value in key_dict.items(): 
     if keyword in keywords_list: 
      found_imgs = found_imgs.union(set(value)) 
    return found_imgs 

print find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png', '3.png']}, ['dog', 'animal']) 

EDITしてみてください。あなたに基づいてlistバージョンを追加します。

def find_images_with_keyword(key_dict, keywords_list): 
    new_list = [] 
    for item in key_dict.items(): 
     key, filenames = item 
     if key in keywords_list: 
      for filename in filenames: 
       if filename not in new_list: # add this 
        new_list.append(filename) 
    return new_list 
+0

が何をして設定され、労働組合? – bigd

+0

[セット](https://docs.python.org/2/library/sets.html) –

+0

私の新しい投稿を見て、たくさん手伝ってください。 –

関連する問題