简体   繁体   English

改进Python列表理解以消除嵌套数组

[英]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. 我想知道如何在不使长度为7的数组的情况下将7次添加到新列表中。我试图摆脱在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序列生成每7个数字的序列,直到年总天数,所以这也可行:

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 list只是一个重复的整数序列,从1开始,每个整数重复7次,一直到sum(months) // 7 ,包括sum(months) // 7 ,所以您可以这样做:

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. 这在列表推导中使用了一个嵌套循环,该循环仅迭代7次。 You could also use the itertools.product() iterator to flatten this to a single loop: 您还可以使用itertools.product()迭代器将其展平为单个循环:

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. 这将使用7个None引用的元组添加重复,然后循环将忽略这些值。

Neither version needs weeks to exist. 这两个版本都不需要weeks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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