[英]Loop Issue with Local Variable
我正在使用Python(3.x)創建用於分配的簡單程序。 它需要一個多行輸入,並且如果有多個連續的空格,則會將其剝離,並用一個空格替換。 [這是簡單的部分。]它還必須在整個輸入中打印出最連續的空格的值。
例:
input = ("This is the input.")
應打印:
This is the input.
3
我的代碼如下:
def blanks():
#this function works wonderfully!
all_line_max= []
while True:
try:
strline= input()
if len(strline)>0:
z= (maxspaces(strline))
all_line_max.append(z)
y= ' '.join(strline.split())
print(y)
print(z)
if strline =='END':
break
except:
break
print(all_line_max)
def maxspaces(x):
y= list(x)
count = 0
#this is the number of consecutive spaces we've found so far
counts=[]
for character in y:
count_max= 0
if character == ' ':
count= count + 1
if count > count_max:
count_max = count
counts.append(count_max)
else:
count = 0
return(max(counts))
blanks()
我知道這可能效率極低,但似乎幾乎可以正常工作。 我的問題是這樣的:我想在循環完成后將所有內容追加到all_lines_max,然后打印該列表的最大值。 但是,似乎沒有一種方法可以在不執行每一行的情況下打印該列表的最大值,如果這樣做是有道理的。 對我復雜的代碼有什么想法嗎?
只需打印all_line_max
的max
,就在您當前打印整個列表的位置:
print(max(all_line_max))
但將其保留在頂層 (因此請降低一次):
def blanks():
all_line_max = []
while True:
try:
strline = input()
if strline:
z = maxspaces(strline)
all_line_max.append(z)
y = ' '.join(strline.split())
print(y)
if strline == 'END':
break
except Exception:
break
print(max(all_line_max))
並刪除print(z)
調用,該調用將每行打印最大空白數。
每次發現空間時, maxspaces()
函數都會將count_max
添加到counts
列表中; 不是最有效的方法。 您甚至不需要在此保留列表。 count_max
需要移出循環,然后才能正確反映最大空間數。 您也不必將句子變成列表,您可以直接在字符串上循環:
def maxspaces(x):
max_count = count = 0
for character in x:
if character == ' ':
count += 1
if count > max_count:
max_count = count
else:
count = 0
return max_count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.