如何在迭代或循环时将最后一个索引与列表中的第一个索引进行比较

时间:2016-05-03 11:52:12

标签: python-3.x

我想在循环或地图步骤中将最后一个索引与第一个索引进行比较。我想要这样的东西使用' map':

def difference(angle):
    return angle.next() - angle

angles = [90,180,270]
diff = list(map(difference,angles))
print(diff)

或类似的东西使用' for'循环:

angles = [90,180,270]
diff = []
for angle in angles:
    diff.append(angles.next()-angle)

print(diff)

他们不工作。你不能在int类型上调用.next()

这确实有效,但看起来非常混乱:

angles = [90,180,270]
i = 0
diff = []
angles.append(angles[0])
while i <len(angles)-1:
    diff.append(angles[i+1]-angles[i])
    i += 1

print(diff)

有更整洁的解决方案吗?我不觉得我应该将第一个索引追加到最后才能执行此操作。

2 个答案:

答案 0 :(得分:1)

使用zip将原始列表和移动了一个项目的相同列表组合在一起:

diff = [left-right for left, right in zip(angles, angles[1:]+angles[:1])]

对于angles = [90,180,270],结果为[-90, -90, 180]

或者反过来(从右边减去左边的值):

diff = [right-left for left, right in zip(angles, angles[1:]+angles[:1])]

对于angles = [90,180,270],结果为[90, 90, -180]

如果您不想要,也可以使用abs(...)删除该符号:

diff = [abs(left-right) for left, right in zip(angles, angles[1:]+angles[:1])]

对于angles = [90,180,270],结果为[90, 90, 180]

答案 1 :(得分:1)

另一种方法:

diff = []
while i <len(angles)-1:
    diff.append(angles[i+1]-angles[i])
    i += 1
diff.append(angles[len(angles)-1]-angles[0])