python -++增量运算符的等价物是什么?

标签 python iterator increment

我正试图在 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/

相关文章:

JAVA - 使用按键增加 Selenium 上的输入数字

c++ - 数组值未正确递增

python - 此错误消息 {"error": {"id" :"unauthorized" ,"message" :"Invalid credentials provided."}} when I click on Heroku Postgres

python - 迭代器失效的规则是什么?

c++ - 迭代器问题

c++ - C++基于范围的for循环会调用迭代器的析构函数吗?

java - 如何使用模运算符递增和递减整数

javascript - 如何使用 Flask 创建两个依赖的动态下拉列表

python - 屏幕尺寸变化时 Kivy 图像更新

python - 从html页面获取相关链接