获取python for循环中的第一个和最后一个项目 [英] Getting the first and last item in a python for loop

查看:782
本文介绍了获取python for循环中的第一个和最后一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ c>从日历导入日历
$ b $ cal =日历(6)
month_dates = cal.itermonthdates(year,month)
在date_dates中的日期:
if(is第一个项目):#这是假的
month_start = date
如果(是最后一个项目):#so是这个
month_end = date

这段代码试图获得这个月结束的一周中的第一天,以及这个月结束的一周的最后一天。例如:对于六月,月开始应该评估到5/31/09。即使从五月份的技术情况来看,这是六月份的第一天。



月份日期是一个生成器,所以我不能做[ :-1]的东西。什么是更好的方法来处理这个问题?

解决方案

我会强制它在开始列表:

$从日历导入b
$ b

 日历SUNDAY 
$ b cal =日历(SUNDAY)
month_dates = list(cal.itermonthdates (年,月))

month_start = month_dates [0]
month_end = month_dates [-1]

因为只能有42天(计数前置和后置上下文),所以对性能的影响可以忽略不计。另外,使用SUNDAY比幻数好。


Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?

from calendar import Calendar

cal = Calendar(6)
month_dates = cal.itermonthdates(year, month)
for date in month_dates:
    if (is first item):     # this is fake
        month_start = date
    if (is last item):      # so is this
        month_end = date

This code is attempting to get the first day of the week the month ends on, and the last day of the week the month ends on. Example: for June, month-start should evaluate to 5/31/09. Even though it's technically a day in May, it's the first day of the week that June begins on.

Month-dates is a generator so i can't do the [:-1] thing. What's a better way to handle this?

解决方案

I would just force it into a list at the beginning:

from calendar import Calendar, SUNDAY

cal = Calendar(SUNDAY)
month_dates = list(cal.itermonthdates(year, month))

month_start = month_dates[0]
month_end = month_dates[-1]

Since there can only be 42 days (counting leading and tailing context), this has negligible performance impact.

Also, using SUNDAY is better than a magic number.

这篇关于获取python for循环中的第一个和最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆