簡體   English   中英

Python循環時的賦值條件

[英]Assignment Condition in Python While Loop

在C中,人們可以做到

while( (i=a) != b ) { }

但是在Python中,它似乎不可能。

while (i = sys.stdin.read(1)) != "\n":

生成

    while (i = sys.stdin.read(1)) != "\n":
         ^
SyntaxError: invalid syntax

^應該在=

有解決方法嗎?

使用休息:

while True:
    i = sys.stdin.read(1)
    if i == "\n":
       break
    # etc...

您可以使用內置函數iter()使用雙參數調用方法來完成此操作:

import functools
for i in iter(fuctools.partial(sys.stdin.read, 1), '\n'):
    ...

這方面的文件:

iter(o[, sentinel])
...
如果給出第二個參數sentinel ,則o必須是可調用對象。 在這種情況下創建的迭代器將為每個對next()方法的調用調用o而不帶參數; 如果返回的值等於sentinel ,則會引發StopIteration ,否則返回該值。

第二種形式的iter()一個有用的應用是讀取文件的行直到達到某一行。 以下示例讀取文件,直到readline()方法返回空字符串:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)

沒有functools的版本:

for i in iter(lambda: sys.stdin.read(1), '\n'):

啟動Python 3.8 ,並引入賦值表達式(PEP 572):=運算符),現在可以捕獲表達式值(此處為sys.stdin.read(1) )作為變量,以便在正文中使用它while

while (i := sys.stdin.read(1)) != '\n':
  do_smthg(i)

這個:

  • sys.stdin.read(1)分配給變量i
  • 比較i\\n
  • 如果條件有效,請輸入可以使用iwhile主體

就個人而言,我喜歡使用break和Mark的答案,但你也可以這樣做:

a = None
def set_a(x):
    global a
    a = x
    return a

while set_a(sys.stdin.read(1)) != '\n':
    print('yo')

雖然我不推薦它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM