[英]While accessing a list through a “for” loop i.e. “for x in list:” , is there a way to access the “x+1” item in the list in the same loop?
通过for
循环(即for x in list:
的x+1
访问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
用作变量名。
您有多个选择。
一种是使用enumarate()
for counter, x in enumerate(a_list):
print(str(x+a_list[counter+1]))
在最后一次迭代中将抛出IndexError,因此您也必须处理这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.