python - 通过 "for"循环(即 "for x in list:")访问列表时,有没有办法在同一循环中访问列表中的 "x+1"项?

标签 python list loops

通过for循环访问列表时,即for x in list:,有没有办法访问x+1 同一循环中列表中的项目?

例如,

list = [1 ,2 ,3 ,4]

有没有办法像 1+2、2+3、3+4 这样相加

for x in list:
    print(x+(x+1))

最佳答案

您可以按索引而不是值进行循环,并确保在倒数第二个索引处停止,以避免在访问下一个索引时出现 IndexError: list index out of range 异常:

l = [1 ,2 ,3 ,4]

for i in range(len(l) - 1):
    print(l[i] + l[i + 1])

然而,更 Pythonic 的方法是使用其自身的右移版本zip您的列表:

l = [1 ,2 ,3 ,4]

for i, j in zip(l, l[1:]):
    print(i + j)

PS:避免使用内置类型list作为变量名。

关于python - 通过 "for"循环(即 "for x in list:")访问列表时,有没有办法在同一循环中访问列表中的 "x+1"项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57844289/

相关文章:

arrays - 如何遍历多个 UILabel

python - 需要 Numpy 帮助 : how to use boolean values to calculate ranges and add values together within ranges?

python - 两个列表查找值

java - for 循环到 while 循环

java - 将循环中的数据保存到数组

java - 列表的范围和生命周期

python - pandas 根据缺失值的条件逻辑添加新列

python - Linux 上 VSCode 中 Python 的 VSCode-Python 大纲 View 不起作用

python - Python3 list.copy() 为何是浅拷贝?

list - 避免在 Erlang 中将数字转换为字符