Peter Otten wrote: > Ken G. wrote: > >> Assuming I have the following list and code how do I best be able >> rearrange the list as stated below: >> >> list = [0, 0, 21, 35, 19, 42] >> >> Using print list[2:6] resulted in the following: >> >> 2 21 >> 3 35 >> 4 19 >> 5 42 >> >> I would like to rearrange the list as follow: >> >> 5 42 >> 3 35 >> 2 21 >> 4 19 >> >> I tried using list.reverse() and print list[0,6] and it resulted in: >> >> [42, 19, 35, 21, 0, 0] or as printed: >> >> 0 42 >> 1 19 >> 2 35 >> 3 21 >> 4 0 >> 5 0 >> >> In another words, I would desire to show that: >> >> 5 appears 42 times >> 3 appears 35 times >> 2 appears 21 times >> 4 appears 19 times >> >> but then I lose my original index of the numbers by reversing. How do I >> best keep the original index number to the rearrange numbers within a >> list? > > Don't rearrange the original list, make a new one instead: > >>>> frequencies = [0, 0, 21, 35, 19, 42] >>>> wanted_indices = [5, 3, 2, 4] >>>> [frequencies[i] for i in wanted_indices] > [42, 35, 21, 19] > > Or look up the values as you print them: > >>>> for i in wanted_indices: > ... print(i, "appears", frequencies[i], "times") > ... > 5 appears 42 times > 3 appears 35 times > 2 appears 21 times > 4 appears 19 times > > The expression [frequencies[i] for i in wanted_indices] is called "list > comprehension" and is a shortcut for a loop: > >>>> result = [] >>>> for i in wanted_indices: > ... result.append(frequencies[i]) > ... >>>> result > [42, 35, 21, 19]
Oops, it occurs to me that you may want the most frequent indices rather than specific indices. You can achieve that with >>> def lookup_frequency(index): ... return frequencies[index] ... >>> wanted_indices = sorted(range(len(frequencies)), key=lookup_frequency, reverse=True) >>> wanted_indices [5, 3, 2, 4, 0, 1] >>> wanted_indices[:4] [5, 3, 2, 4] You may also want to look at the collections.Counter class: >>> import collections >>> c = collections.Counter() >>> for i, freq in enumerate(frequencies): ... c[i] = freq ... >>> c.most_common(4) [(5, 42), (3, 35), (2, 21), (4, 19)] >> for key, freq in c.most_common(4): ... print(key, "appears", freq, "times") ... 5 appears 42 times 3 appears 35 times 2 appears 21 times 4 appears 19 times _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor