pythonista如何在Python 3中编写与增量运算符等效的代码?

时间:2015-09-14 19:22:48

标签: python iterator increment

我正在尝试在Python中找到正确的方法来完成以下任务(不能按照书面形式工作):

margin-right: 15px

不幸的是(至少对我而言),Python中不存在++运算符或语句,作为将变量递增1的方法,但使用

myList = ["a", "b", "c"]
myCounter = 5

for item in myList:
  print("""Really long text 
in which I need to put the next iteration of myCounter (""", myCounter++, """) followed 
by a lot more text with many line breaks
followed by the next iteration of myCounter (""", myCounter++, """) followed by even
more long text until finally we get to the next
iteration of the for loop.""", sep='')
当我想要打印变量并同时递增变量时,

在它的位置似乎不起作用。我希望它首次通过for循环打印5和6,然后在下一次打印时打印7和8,然后在最后一次打印时打印9和10。应该如何在Python 3中完成?

2 个答案:

答案 0 :(得分:4)

我可能会考虑使用itertools.count

import itertools

myCounter = itertools.count(5)
for item in myList:
    print("la la la.", next(myCounter), "foo foo foo", next(myCounter))

如果您希望避免导入,您可以很容易地编写自己的生成器来执行此类操作:

def counter(val=0):
    while True:
        yield val
        val += 1

答案 1 :(得分:3)

我只是在print语句中使用myCounter + 1myCounter + 2,然后在它之外将myCounter增加2.示例 -

myList = ["a", "b", "c"]
myCounter = 5

for item in myList:
  print("""Really long text 
in which I need to put the next iteration of myCounter (""", myCounter + 1, """) followed 
by a lot more text with many line breaks
followed by the next iteration of myCounter (""", myCounter + 2, """) followed by even
more long text until finally we get to the next
iteration of the for loop.""", sep='')
  myCounter += 2