所以我的问题是 - 我有一个类似的代码:
test_text = "lorem ipsum dolor sit amet"
for each in test_text:
#do some stuff
虽然它肯定适用于当前"突出显示的字母"通过for,我不能对之前的那些做任何事情而没有我将在每次迭代中递增的额外变量,以便我可以解决test_text [said_variable]。我的意思是 - 让我们说,对于每个用户想要的字母,我必须在上述字母之前打印出五个索引位置的字母 - 没有附加变量,我无法做到这一点。有人可以帮忙吗?我可以在之前(或之后)处理现在正在处理的事情而不必像那样玩吗?
我很抱歉这个新问题,但我刚刚开始使用Python而且无法找到任何相关内容。
答案 0 :(得分:8)
我不相信你可以在没有第二个变量的情况下做到这一点,但你不必手动增加它:
for i, each in enumerate(test_text):
print each, test_text[i-5]
请注意,否定列表索引将转到列表的末尾,即test_text[-1]
将返回最后一个字符,因此如果您不这样做,则必须在i-5
上添加一个检查想要这种行为。
答案 1 :(得分:4)
正如Lenna所说,枚举是一种在循环时跟踪位置索引的好方法。
也就是说,只要text[i-5]
,您的i < 5
查询就会失败。相反,请尝试使用切片访问i
附近的范围。
>>> test_text = "lorem ipsum dolor sit amet"
>>> for i, c in enumerate(test_text):
print repr(c), "is surrounded by", repr(test_text[i-5:i+5])
'l' is surrounded by ''
'o' is surrounded by ''
'r' is surrounded by ''
'e' is surrounded by ''
'm' is surrounded by ''
' ' is surrounded by 'lorem ipsu'
'i' is surrounded by 'orem ipsum'
'p' is surrounded by 'rem ipsum '
's' is surrounded by 'em ipsum d'
'u' is surrounded by 'm ipsum do'
'm' is surrounded by ' ipsum dol'
' ' is surrounded by 'ipsum dolo'
'd' is surrounded by 'psum dolor'
'o' is surrounded by 'sum dolor '
'l' is surrounded by 'um dolor s'
'o' is surrounded by 'm dolor si'
'r' is surrounded by ' dolor sit'
' ' is surrounded by 'dolor sit '
's' is surrounded by 'olor sit a'
'i' is surrounded by 'lor sit am'
't' is surrounded by 'or sit ame'
' ' is surrounded by 'r sit amet'
'a' is surrounded by ' sit amet'
'm' is surrounded by 'sit amet'
'e' is surrounded by 'it amet'
't' is surrounded by 't amet'