本文介绍了Pythonic通告列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个清单,
l = [1, 2, 3, 4, 5, 6, 7, 8]
我想获取任意元素的索引及其相邻元素的值.例如,
I want to grab the index of an arbitrary element and the values of its neighbors. For example,
i = l.index(n)
j = l[i-1]
k = l[i+1]
但是,对于i == len(l) - 1
的边缘情况,这将失败.所以我想我会把它包起来,
However, for the edge case when i == len(l) - 1
this fails. So I thought I'd just wrap it around,
if i == len(l) - 1:
k = l[0]
else:
k = l[i+1]
是否有一种Python方式来做到这一点?
Is there a pythonic way to do this?
推荐答案
您可以使用模运算符!
i = len(l) - 1
jIndex = (i - 1) % len(l)
kIndex = (i + 1) % len(l)
j = l[jIndex]
k = l[kIndex]
或者,不那么冗长:
k = l[(i + 1) % len(l)]
这篇关于Pythonic通告列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!