简体   繁体   中英

Improving Python List Comprehension to Eliminate Nested Arrays

I am trying to create a list comprehension, that improves upon one I already have.

I have a list of numbers representing the lengths of a month.

months = [35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28] 

I want to expand this array into an array with a length of the full year, and every value in that array representing which week that day (index) falls into.

Currently I am doing this with two list comprehensions.

weeks = [w for w in range(sum(months)) if w % 7 == 0]
weeks_expanded = [day for week in [[d + 1] * 7 for d in range(len(weeks))] for day in week]

I wanted to know how I could add something to the new list 7 times without making it an array of length 7. I'm trying to get rid of the added step of flattening my inner list comprehension in weeks_expanded. [[d + 1] * 7 for d in range(len(weeks))]

Thanks for the help.

You are basically generating a sequence of every 7th number for the weeks sequence, up to the year-total number of days, so this works too:

weeks = range(0, sum(months), 7)

weeks_expanded list is just a sequence of repeated integers, starting at 1, each repeated 7 times, up to and including sum(months) // 7 , so you could just do this:

weeks_expanded = [wn for wn in range(1, (sum(months) // 7) + 1) for __ in range(7)]

This uses a nested loop in the list comprehension, that just iterates 7 times. You could also use the itertools.product() iterator to flatten this to a single loop:

from itertools import product

weeks_expanded = [wn for wn, __ in product(range(1, (sum(months) // 7) + 1), (None,) * 7)]

This uses a tuple of 7 None references to add the repetition, the loop then ignores those values.

Neither version needs weeks to exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM