我有一系列的项目(按月数计算),现在我想按月对它们进行分组,所以我想转一下:
(1, True), ... (31, True), (1, False) ...(28, True),...这方面:
[(1, True), ... (31, True)], [(1, False) ...(28, True)],...我正在使用python 3。我应该怎么做呢?
发布于 2015-08-22 13:59:23
您可以使用生成器函数,在每次第一个值下降而不是上升时生成一个新组:
def group_by_month(items):
month = []
for day, flag in items:
if month and month[-1][0] > day:
# new month starting
yield month
month = []
month.append((day, flag))
if month:
yield month您可以在生成的月份中迭代,也可以使用以下方法将所有月份聚集在一个大列表中:
grouped = list(group_by_month(items))发布于 2015-08-22 14:06:18
下列措施应能发挥作用:
days = [(1, True), (2, False), (31, True), (1, False), (2, True)]
month = []
grouped_by_month = []
last = (0, False)
for pair in days:
if pair < last:
grouped_by_month.append(month)
month = []
month.append(pair)
last = pair
grouped_by_month.append(month)
print(grouped_by_month)给予:
[[(1, True), (2, False), (31, True)], [(1, False), (2, True)]]https://stackoverflow.com/questions/32156895
复制相似问题