[英]how to change for loop to a while loop
我在將代碼轉換為 while 循環時遇到問題? 我將代碼作為 for 循環完成,但它必須是 while 循環。 我不太確定如何開始?
這就是問題所要求的:
編寫 function split() 以使用給定列表中的 while 循環每隔第 4 個元素拆分一個列表。 給定列表:s =“ellepeepizzikeeksaasannanoonnaan”
這是我的代碼:
def split(s):
s = 'ellepeepizzikeeksaasannanoonnaan'
split_string = []
n = 4
for index in range(0, len(s), n):
split_string.append(s[index : index + n])
print(split_string)
當涉及到循環時, for
只是while
的一個特定情況。 以基本for
循環為例:
for index in range(10):
print(index)
寫成一個while
循環:
index = 0
while index < 10:
print(index)
index += 1
如果您想每隔 n 項向 select 添加跳過功能,我們可以這樣做:
n = 4
index = 0
while index < 10:
print(index)
index += n
這樣,我們從 x=0 開始,每次將其遞增 n。
簡單的方法是這樣的:
def split(s):
split_string = []
n = 4
index = 0
while(len(s) != 0):
split_string.append(s[:n])
s = s[n:]
print(split_string)
s = "ellepeepizzikeeksaasannanoonnaan"
split(s)
社區已經徹底回答了這個問題,所以我決定讓 go 偏離軌道一點。 不管它是不是學校練習,我想多加點醬汁來展示另一種方式,你可以用 go 來了解它!
這是您訂購的溫和 while 循環:
def split(s, n, index=0, split_string=[]):
while(len(s) != 0):
split_string.append(s[:n])
s = s[n:]
print(split_string)
split(s="ellepeepizzikeeksaasannanoonnaan", n=4)
嗯,這很無聊……我們來探索一下怎么樣!
變辣:
我喜歡@Loai 的回答,但添加了一些遞歸耀斑->
def spicy_split(s, n, split_string=[]):
if len(s) != 0:
split_string.append(s[:n])
s = s[n:]
return spicy_split(s, n, split_string)
else:
print(split_string)
s = "ellepeepizzikeeksaasannanoonnaan"
spicy_split(s=s,n=4)
耶。 仍然得到相同的響應答案。 *比利·梅斯配音“但還有更多!”
哦 Lawd 太熱了:
讓我向你介紹發電機的奇妙世界,不像我在 10 年級。這些很酷嗎? 為什么,嗯,因為他們可以迭代一個巨大的數據集,但只將其操作的給定部分加載到 RAM 中。 並允許您對計算機可能會失敗的事物進行計算。 讓我們看看->
# generator
def oh_lawd_thats_HOT(s, n):
while len(s) > 0:
split = s[:n]
s = s[n:]
yield split
s = "ellepeepizzikeeksaasannanoonnaan"
# the oh_lawd_thats_HOT function is actually an iterable! Have a look:
print([s for s in oh_lawd_thats_HOT(s=s,n=4)])
大多數人可能已經“與這個白痴一起完成了”,並且在繼續之前可能已經讓我被遺忘了。 但是這個白痴沒有放棄!
頂級繩索:
我:“嘿,你想要一些免費的異步嗎?” 其他人:“不,謝謝,我不吸毒。”
我們現在正式變得時髦。
好吧,我向您介紹異步生成器,就像常規生成器一樣,但速度快 2 倍,當您的同事審查您的代碼時,他們可能會混淆 3 倍。 在生產應用程序中中斷的可能性是 4 倍。 確保你的地位! ->
import asyncio
# async generator
async def OFF_THE_TOP_ROPES(s, n, split_string=[]):
for index in range(0, len(s), n):
yield split_string.append(s[index : index + n])
s = "ellepeepizzikeeksaasannanoonnaan"
async for s in OFF_THE_TOP_ROPES(s=s,n=4):
print(s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.