yield
Python中关键字的用途是什么?它有什么作用?
例如,我试图理解这段代码1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
Run Code Online (Sandbox Code Playgroud)
这是来电者:
result, candidates = [], [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
Run Code Online (Sandbox Code Playgroud)
_get_child_candidates
调用该方法时会发生什么?列表是否返回?单个元素?它又被召唤了吗?后续通话何时停止?
1.代码来自Jochen Schulz(jrschulz),他为度量空间创建了一个很棒的Python库.这是完整源代码的链接:模块mspace.
我正在处理Python中的日期,我需要将它们转换为UTC时间戳,以便在Javascript中使用.以下代码不起作用:
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)
Run Code Online (Sandbox Code Playgroud)
将日期对象首先转换为datetime也无济于事.我试过这个链接的例子,但是:
from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)
Run Code Online (Sandbox Code Playgroud)
现在要么:
mktime(utc.localize(input_date).utctimetuple())
Run Code Online (Sandbox Code Playgroud)
要么
mktime(timezone('US/Eastern').localize(input_date).utctimetuple())
Run Code Online (Sandbox Code Playgroud)
确实有效.
所以一般的问题:如何根据UTC获得自纪元以来转换为秒的日期?
我正在尝试计算给定日期的第n个工作日.例如,我应该能够计算给定日期的月份的第3个星期三.
我写了两个版本的函数应该这样做:
from datetime import datetime, timedelta
### version 1
def nth_weekday(the_date, nth_week, week_day):
temp = the_date.replace(day=1)
adj = (nth_week-1)*7 + temp.weekday()-week_day
return temp + timedelta(days=adj)
### version 2
def nth_weekday(the_date, nth_week, week_day):
temp = the_date.replace(day=1)
adj = temp.weekday()-week_day
temp += timedelta(days=adj)
temp += timedelta(weeks=nth_week)
return temp
Run Code Online (Sandbox Code Playgroud)
控制台输出
# Calculate the 3rd Friday for the date 2011-08-09
x=nth_weekday(datetime(year=2011,month=8,day=9),3,4)
print 'output:',x.strftime('%d%b%y')
# output: 11Aug11 (Expected: '19Aug11')
Run Code Online (Sandbox Code Playgroud)
两个函数中的逻辑显然是错误的,但我似乎无法找到错误 - 任何人都可以发现代码有什么问题 - 我如何修复它以返回正确的值?
按照这个答案,我试图获取当月最后一个星期四的日期。但是我的代码没有跳出循环。
from datetime import datetime
from dateutil.relativedelta import relativedelta, TH
todayte = datetime.today()
cmon = todayte.month
nthu = todayte
while nthu.month == cmon:
nthu += relativedelta(weekday=TH(1))
#print nthu.strftime('%d%b%Y').upper()
Run Code Online (Sandbox Code Playgroud)