[英]checking next element in for loop
假设我有这个数组:
arr = ["foo","bar","hey"]
我可以使用以下代码打印"foo"
字符串:
for word in arr:
if word == "foo":
print word
但我还要检查下一个word
是否等于"bar"
然后应打印"foobar"
如何检查for循环中的下一个元素?
for i in range(len(arr)):
if arr[i] == "foo":
if arr[i+1] == 'bar':
print arr[i] + arr[i+1]
else:
print arr[i]
列表中的项目可以通过其索引来引用。 使用enumerate()
方法来接收一个迭代器以及每个列表元素(最好是实例化和递增自己的C模式),您可以像这样进行操作:
arr = ["foo","bar","hey"]
for i, word in enumerate(arr):
if word == "foo" and arr[i+1] == 'bar':
print word
但是,当您到达列表的末尾时,将遇到需要处理的IndexError
,或者您可以首先获取列表的长度( len()
)并确保i < max
。
跟踪前一个值,而不是检查下一个值:
last = None
for word in arr:
if word == "foo":
print word
if last == 'foo' and word == 'bar':
print 'foobar'
last = word
跟踪已经通过的内容比偷看更容易。
您也可以使用zip来实现:
for cur, next in zip(arr, arr[1:]):
if nxt=='bar':
print cur+nxt
但请记住,由于len(ar[1:])
将为2,因此迭代次数将仅为2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.