Python List Comprehension Örnek

Hamdi Yılmaz
1 min readDec 9, 2021
def word_search(doc_list, keyword):
"""
Takes a list of documents (each document is a string) and a keyword.
Returns list of the index values into the original list for all documents
containing the keyword.
Example:
doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
>>> word_search(doc_list, 'casino')
>>> [0]
"""
donus_list= []
for i in range(len(doc_list)):
kelimeler = doc_list[i].split()

kelimeler = [kelime.lower().rstrip(",.") for kelime in kelimeler]
if keyword in kelimeler:
donus_list.append(i)

return donus_list
q2.check()

comprehension

return [ind 
for ind, doc in enumerate(doc_list)
if keyword in [kelime.rstrip(",.")
for kelime in doc.lower().split()
]
]

olayın devamı

def multi_word_search(doc_list, keywords):
"""
Takes list of documents (each document is a string) and a list of keywords.
Returns a dictionary where each key is a keyword, and the value is a list of indices
(from doc_list) of the documents containing that keyword
>>> doc_list = ["The Learn Python Challenge Casino.", "They bought a car and a casino", "Casinoville"]
>>> keywords = ['casino', 'they']
>>> multi_word_search(doc_list, keywords)
{'casino': [0, 1], 'they': [1]}
"""

return {key: word_search(doc_list, key) for key in keywords}
q3.check()

kaynak : https://www.kaggle.com/hamdiy/exercise-strings-and-dictionaries/edit

--

--