我正试图在 Python 中找到正确的方法来完成以下任务(这与写的不一样):
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='')
不幸的是(至少对我而言),Python 中不存在++ 运算符或语句作为将变量递增 1 的方法,而是使用
myCounter += 1
当我想打印变量并同时递增它时,在它的位置似乎也不起作用。我希望它第一次通过 for 循环打印 5 和 6,然后下一次打印 7 和 8,最后一次打印 9 和 10。这应该如何在 Python 3 中完成?
最佳答案
我可能会考虑使用 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
关于python -++增量运算符的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32572351/