I am am trying to improve my coding, and algorithm performance by replacing for
loops with list comprehensions, generators, and iterators.
I am having a hard time rapping my head around how to implement the tools in itertools
, and I would appreciate any help you could give.
I am trying to initialize an list with value 0
from for a certain range of indices. Here are two ways that I came up with:
count_list = [0 for index in range(4 ** k)]
and
total_index = list(range(4 ** k))
count_list = [0 for index in total_index]
(k represents an integer of the the number letter in a word made of a 4 letter alphabet)
When I timed the code in Python 3.4, it turned out that the first, using the generator was a significantly faster method when looking at it in isolation, however when I had to reuse the 4 ** k
index for another loop, the methods ended up timing at about the same speed.
What I have been struggling to figure out is how I can use an iterator to replicate this initialization. I know if I wanted to create a list of all of the numbers in the index I could just use list(range())
or I could use
index_list = [index for index, values in enumerate(words)]
I am just not sure how to get it to assign the value 0
to each element using something like that.
I am also wondering how I might use list comprehension to get rid of this for
loop. I am guessing I need something like map, but I am not sure how to implement.
for index in range(4 ** k):
if frequency_array[index] >= t:
clump[index] = 1
Thank you.
To initialize your list with 0
:
>>> my_list = [0] * 10
>>> my_list
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
If you want to use list
comprehension instead of for
loop, you can do it this way:
>>>t = 3
>>>l = [1,2,3,1,2,3,1,2,3,3,2,1]
>>>new_list = [1 if l[i] >= t else l[i] for i in range(len(l))]
>>>new_list
[1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1]
Also, you can use the AND - OR
combination, this way:
>>>new_list = [l[i] >= t and 1 or l[i] for i in range(len(l))]
>>>new_list
[1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1]