我试图在每个循环中迭代一个arraylist保存连续值的最高/最低差异。
e1=([ 0 , 0, 0, 0, 15, 28, 28, 28, 27, 27, 35, 44, 43, 43, 42, 39])
Hodiffmax = 0
Hodiffmin = 0
for k in e1:
diff1= e1[k+1] - e1[k]
if diff1 > Hodiffmax:
Hodiffmax=diff1
if diff1 < Hodiffmin:
Hodiffmin=diff1
问题是我得到一个&#34;索引超出范围&#34;错误。如何用[k + 1]迭代一个arraylist?我现在尝试了很多东西,但我没有变得更聪明。我感谢任何帮助!
编辑(既不起作用):
for k in e1:
for w in k:
diff1= e1[w+1] - e1[w]
if diff1 > Hodiffmax:
Hodiffmax=diff1
if diff1 < Hodiffmin:
Hodiffmin=diff1
错误:对于w中的k - TypeError:&#39; numpy.int32&#39;对象不可迭代
答案 0 :(得分:3)
使用[y - x for x, y in zip(e1, e1[1:])]
,您可以获得连续的差异,而无需担心索引:
>>> e1 = [ 0 , 0, 0, 0, 15, 28, 28, 28, 27, 27, 35, 44, 43, 43, 42, 39]
>>> l = [y - x for x, y in zip(e1, e1[1:])]
>>> Hodiffmax, Hodiffmin = max(l), min(l)
>>> Hodiffmax, Hodiffmin
15, -3
答案 1 :(得分:2)
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
from itertools import izip_longest # required by grouper
i = [0, 0, 0, 0, 15, 28, 28, 28, 27, 27, 35, 44, 43, 43, 42, 39]
lowest = None
highest = None
for z,q in grouper(i, 2):
v = z-q
if v < lowest:
lowest = v
if v > highest:
highest = v
print(lowest)
print(highest)
答案 2 :(得分:0)
这里的问题是你正在迭代列表的元素。通过做
对于e1中的k:
NoMethodError: undefined method `css_value' for #<Capybara::Poltergeist::Node tag="div">
将获取k
上元素的值。 e1
等等。你想要的是迭代列表的范围。
k=0, k=0, k=0, k=0, k=15, k=28
for k in range(len(e1)):
将获取k
上的索引值。 e1
等等。我想你正在寻找这样的东西:
k=0, k=1, k=2, k=3, k=4, k=5