Python 如何将for循环更改为while循环

Python 如何将for循环更改为while循环,python,while-loop,split,Python,While Loop,Split,我无法将代码转换为while循环?我将代码作为for循环完成,但它必须是while循环。我不太确定如何开始 这就是问题所要求的: 编写一个函数split(),使用给定列表中的while循环,每隔4个元素分割一个列表。 给定列表:s=“Ellepeepizzikeeksaasannanoonnanan” 这是我的密码: def split(s): s = 'ellepeepizzikeeksaasannanoonnaan' split_string = [] n = 4

我无法将代码转换为while循环?我将代码作为for循环完成,但它必须是while循环。我不太确定如何开始

这就是问题所要求的:

编写一个函数split(),使用给定列表中的while循环,每隔4个元素分割一个列表。 给定列表:s=“Ellepeepizzikeeksaasannanoonnanan”

这是我的密码:

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
只是
的一个特例,而
涉及循环时。采用基本的
for
循环:

for index in range(10):
   print(index)
index = 0 
while index < 10:
   print(index)
   index += 1
写为
while
循环:

for index in range(10):
   print(index)
index = 0 
while index < 10:
   print(index)
   index += 1
index=0
当指数<10时:
打印(索引)
指数+=1
如果您想添加跳过功能来选择第n个项目,我们可以这样做:

n = 4
index = 0 
while index < 10:
   print(index)
   index += 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)
n=4
索引=0
当指数<10时:
打印(索引)
索引+=n

这样我们从x=0开始,每次增加n。

简单的方法如下:

n = 4
index = 0 
while index < 10:
   print(index)
   index += 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)

这个问题已经得到了社区的彻底回答,所以我决定稍微偏离正轨一点。不管这是不是学校的运动,我都想多加一些调味汁,以展示你可以做的另一种方式

这是您订购的温和while循环:

def split(s,n,index=0,split_string=[]):
而(len(s)!=0):
拆分字符串。追加(s[:n])
s=s[n:]
打印(拆分字符串)
拆分(s=“Ellepeepizzikeeksaasannanoonnanan”,n=4)
好吧,那是booring。。。我们来探索一下吧

变辣:

我喜欢@Loai的答案,但添加了一些递归flare->

def split\u split(s,n,split\u string=[]):
如果len(s)!=0:
拆分字符串。追加(s[:n])
s=s[n:]
返回split(s、n、split_字符串)
其他:
打印(拆分字符串)
s=“Ellepeepizzikeeksaasannanoonnanan”
辛辣辣(s=s,n=4)
耶!仍然得到相同的回答*比利·梅斯的声音“等等,还有更多!”

噢,那太热了:

让我向你介绍发电机的奇妙世界!不像十年级的我,这些很酷。为什么?好吧,因为它们可以在一个巨大的数据集上迭代,但只能将其操作的给定部分加载到RAM中,并允许您在计算机可能会出现故障的情况下运行计算。让我们看看->

#生成器
def oh_lawd_that_HOT(s,n):
而len(s)>0:
拆分=s[:n]
s=s[n:]
产量分割
s=“Ellepeepizzikeeksaasannanoonnanan”
#oh_lawd_that s_HOT函数实际上是一个iterable!看看:
打印([s代表oh_lawd_that s_HOT(s=s,n=4)])
大多数人可能已经“和这个白痴完蛋了”,可能在继续前进之前就已经把我给遗忘了。但是这个白痴是不会放弃的

脱离顶部绳索:

我:“嘿,你想要一些免费的异步吗?” 其他人:“不,谢谢,我不吸毒。”

我们现在正式变得时髦起来了

好吧,我给你介绍异步发电机!与常规生成器一样,但速度是常规生成器的2倍,在同事查看代码时可能会混淆代码的速度是常规生成器的3倍,在生产应用程序中中断代码的速度是常规生成器的4倍。确保你的站姿!->

导入异步IO
#异步发电机
异步定义脱离顶部绳索(s、n、拆分字符串=[]):
对于范围(0,len(s),n)中的索引:
产生拆分字符串.append(s[index:index+n])
s=“Ellepeepizzikeeksaasannanoonnanan”
在顶部钢丝绳(s=s,n=4)中的s异步:
印刷品

为什么它必须是
循环<代码>for
循环更好。我同意!这只是对它的要求@ggorlenI我猜这是为了一个任务。拆分字符串没有更简单的方法。请记住,for循环只是应用于while循环的语法糖。
s=“ellepeepizzikeeksaasannanoonnanan”
不是列表。请修复缩进。