【问题标题】:Loop with sub assignment in parenthesis括号中带有子赋值的循环
【发布时间】:2014-07-22 16:24:10
【问题描述】:

有没有办法在 Python 中做到这一点? (我知道你可以用 Java 做。)

#PSEUDO CODE!!
while (inp = input()) != 'quit'
    print(inp)

例如在java中,上面的伪代码转换为:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
    String inp;
    while (!(inp = reader.readLine()).equals("quit")) {
        System.out.println(inp);
    }
} catch (IOException io) {
    System.out.println(io.toString());
}

编辑:

...回答...但这是唯一的方法吗?

while True:
    inp = input()
    if inp == 'quit':
        break
    print(inp)
print('eof')

【问题讨论】:

    标签: python loops inline variable-assignment


    【解决方案1】:

    编辑:

    在这种特殊情况下,您可以使用 for 循环和 iter

    for inp in iter(input, 'quit'):
        print(inp)
    

    iter(input, 'quit') 将继续调用input 函数并将其返回值分配给inp,只要该值不等于'quit'


    不,您不能在 Python 中执行内联赋值。 grammar 根本不允许这样做(请记住,赋值是 Python 中的语句)。

    但是你可以这样做:

    while True:            # Loop continuously
        inp = input()      # Get the input
        if inp == 'quit':  # If it equals 'quit'...
            break          # ...then break the loop
        print(inp)         # Otherwise, continue with the loop
    

    大致相当于你想做的。

    【讨论】:

      【解决方案2】:

      您可以在循环之前定义 inp 并在 while 内重新分配:

      inp = None
      while inp  != 'quit':
          print(inp)
          inp = input()
      

      如果你想在进入while循环之前退出,最初设置inp = input()

      inp = input()
      while inp  != 'quit':
          print(inp)
          inp = input()
      

      【讨论】:

      • @PadriacCunningham 很好的优化(我快到了)。但它仍然会打印与 OP 行为不同的“退出”。
      • @JanVlcinsky,您可以将初始值设置为输入,在进入while循环之前将退出。
      猜你喜欢
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 2014-05-02
      • 2014-08-06
      • 2013-11-05
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多