1

所以我的问题是 - 我有这样的代码:

test_text = "lorem ipsum dolor sit amet"

for each in test_text:
   #do some stuff

虽然它确实适用于当前由 for “突出显示”的字母,但如果没有一个额外的变量,我将无法对之前的字母做任何事情,我将在每次迭代中递增,以便我可以解决 test_text [said_variable]。我的意思是-假设对于用户想要的每个字母,我必须打印该字母之前五个索引位置的字母-没有附加变量,我不能这样做。有人可以帮忙吗?我可以在不必像以前那样玩的情况下解决现在正在做的事情之前(或之后)的事情吗?

对于这个新手问题,我很抱歉,但我刚刚开始使用 Python,找不到任何关于此事的信息。

4

2 回答 2

8

我不相信没有第二个变量你可以做到这一点,但你不必手动增加它:

for i, each in enumerate(test_text):
    print each, test_text[i-5]

枚举文档

请注意,否定列表索引将转到列表的末尾,即返回最后一个字符,因此如果您不想要此行为,则test_text[-1]必须添加检查。i-5

于 2012-08-19T18:02:31.470 回答
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'
于 2012-08-19T18:07:23.400 回答