偏移迭代器
我有这个:
d = {"date": tuple(date),"open":tuple(open),"close":tuple(close)}
comp1 = zip(d['open'],d['close'])
for i in comp1:
if i[0]<i[1]:
print "bar up"
if i[0]>i[1]:
print "bar down"
这很好,它告诉我一个柱子是上涨还是下跌,现在我想要“移动”我的循环(比如移动一个位置),但我不知道该怎么写语法。逻辑是:
“如果前一个柱子是上涨的,那么如果当前柱子也是上涨的,就打印‘是’。”
这样说清楚吗?
谢谢!
4 个回答
2
up = lambda a, b: a < b
for prev, b in zip(comp1, comp1[1:]):
if up(*prev) and up(*b):
print "yes"
解释
up = lambda a, b: a < b
这段代码创建了一个接受两个参数的函数。它的意思是判断第一个参数是否小于第二个参数,和使用operator.lt
是一样的。for prev, b in zip(comp1, comp1[1:]):
这行代码使用了序列解包(就像x, y = "xy"
这样),还用了zip() 函数和列表的切片。if up(*prev) and up(*b):
这里使用了*表达式
语法来调用函数,这样可以把列表或元组中的元素拆开传给函数。
2
如果你在使用zip迭代器,为什么不把它提升到一个新高度呢?
comp1 = zip(d['open'],d['close'],d['open'][1:],d['close'][1:])
这样一来,只要这些元组的长度大于1,你就可以不仅遍历这些元组,还可以遍历每个元组中的下一个元素。
0
你可以把现在的循环变成列表推导式,然后再对得到的列表进行遍历:
bars = [i[0]<i[1] for i in comp1]
for b in range(1,len(bars)):
if bars[b] and bars[b-1]:
print "yes"