【问题标题】:How to Use the Program Printed Value for Another Operation in Python?如何在 Python 中将程序打印值用于另一个操作?
【发布时间】:2015-11-27 12:45:59
【问题描述】:

假设我有这个简单的操作:

x = 1
print x+1

如何直接使用“print x+1”中的打印值一遍又一遍地对其进行相同的操作。

我希望输出是:

1
2
3
4
5
6
.
.
.

【问题讨论】:

  • 不打印,将结果分配给变量 - value = x+1
  • 如果我想以循环的方式来做呢?我的意思是我希望python能够识别打印的值并自行使用它而不是每次都将它分配给变量@furas
  • 我不明白你的意思 - 编辑问题并添加示例 - 也许你需要列表来保留所有值

标签: python loops for-loop infinite-loop arithmetic-expressions


【解决方案1】:
x = 1
y = x+1
print y
# then do other/extra operations with "y"

【讨论】:

    【解决方案2】:

    好吧...我会咬...

    import sys
    import io
    
    class Hijacker(io.TextIOWrapper):
        def __init__(self):
            self.last_value = None
            self._odd = True
    
        def write(self, s):
            if self._odd:
                self.last_value = s
            sys.__stdout__.write(str(s))
            self._odd = not self._odd
    
    
        flush = sys.__stdout__ .flush
        read = sys.__stdout__ .read
        readline = sys.__stdout__.readline
        encoding = sys.__stdout__.encoding
        errors = sys.__stdout__ .errors
    
    h = Hijacker()
    sys.stdout = h
    
    print(1)
    print(1 + int(h.last_value))
    print(1 + int(h.last_value))
    

    输出:

    1
    2
    3
    

    这仅在从实际的 shell 运行时才有效,交互式解释器不会有任何它。我也只在 Windows 上尝试过,所以谁知道它是否可以在其他地方工作。不要问我它是如何工作的,它太可怕了,无法理解。也永远不要这样做。就像其他人已经说过的那样,您的方法是错误的。请使用循环和变量!

    【讨论】:

      【解决方案3】:

      我同意 furas 的评论。捕捉打印结果没有什么意义 在大多数情况下。

      如果您有理由希望在字符串中打印输出,您可以这样做 通过使用str() 而不是打印。

      x = 1
      y = str(x+1)
      
      y = y + "do something"
      print y
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-31
        相关资源
        最近更新 更多