Mar-03-2017, 10:52 PM
Hi
Is it possible to have a list comprehension so that I can end up with the following result:
This is the function:
Is it possible to have a list comprehension so that I can end up with the following result:
file_word_list=[('f1',[('you',0.4),('jump',0.12),('the',0.48)]), ('f2',[('hi',0.167),('at',0.333),('you',0.5)])]based on this:
file_word_list=[('f1',[('you',10),('jump',3),('the',12)]), ('f2',[('hi',2),('at',4),('you',6)])]I have a function, which I think gives me what I want, but I was wondering if I could use a comprehension instead. I am unsure how to split the inner tuple though within a comprehension. Also, as you can see from the code, wc_lst is iterated over twice, once to obtain the total word count, and a second time to generate the output and to calculate the term frequency. Would it be possible to only iterate over once?
This is the function:
def calculate_term_frequency(f_wc): f,wc_lst = f_wc qty = 0 wctn = [] for wc in wc_lst: w,c = wc # splitting the inner tuple qty = qty + c for wc in wc_lst: w,c = wc wctn.append( (w,c/qty)) return (f,wctn)