【问题标题】:What is the equivalent of the ++ increment operator?pythonista 如何编写相当于 Python 3 中的 ++ 自增运算符的代码?
【发布时间】:2015-12-10 21:36:38
【问题描述】:

我正在尝试在 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 中完成?

【问题讨论】:

  • 这真的是在任何实际用例中都会出现的情况吗?如果是这样,我会非常好奇地看到它。
  • @polpak - 是的,它出现在一个真实的用例中。我正在打印一堆 XML 消息,每个消息都有一个消息 ID。我要打印的每个元素都有两个消息 ID,因此对于 myList 中的每个元素,我需要打印出带有递增消息 ID 的长 XML 树。

标签: python iterator increment


【解决方案1】:

我可能会考虑使用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

【讨论】:

  • 是否可以导入少于所有的itertools?我仍在学习很多关于 Python 的基础知识,但似乎只为 itertools.count 生成器导入整个模块可能有点过头了。我可以做类似 from itertools import count 之类的事情吗(我试过了,它不起作用,但我想知道是否有类似的东西)
  • @RustyLemur 你可以做from itertools import count。它唯一改变的是myCounter = itertools.count(5)变成myCounter = count(5)
  • @RustyLemur -- 您可以编写自己的计数器,但不能真正进行部分导入。您可以说from itertools import count 来减少当前命名空间中可用的内容,但python 仍会导入整个内容。通常这没什么大不了的(导入的模块被缓存了——所以像itertools 这样流行的东西很可能已经被你正在使用的不同模块导入了)。如果有大问题,你可以编写自己的生成器。
  • 感谢 Morgan 和 mgilson 指出我如何导入只是计数。
【解决方案2】:

我会在 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

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    相关资源
    最近更新 更多