【问题标题】:How can I limit the number of iteration of a loop in a nesting loop function in Python?如何限制Python中嵌套循环函数中循环的迭代次数?
【发布时间】:2020-03-21 23:31:44
【问题描述】:

如何在 Python 的嵌套循环函数中限制循环的迭代次数?

代码:

friends= ['Ali', 'Asma','Amna', 'Izma', 'Omer','Zahid','Bilal','Sarah']
for vowelnames in friends:
    if vowelnames in ('Ali','Asma','Izma','Omer'):
        print('Oh my lovely friend ' + vowelnames + '! ,I would like you to come on my graduation ceremony')
    else:
        for cons in friends[:8]:
            if cons in ('Bilal','Sarah','Zahid'):
                print( cons + " I would like you to come on my graduation ceremony")

【问题讨论】:

  • 你想要的输出是什么?
  • 当你知道你的条件满足时跳出循环或者使用while循环。顺便说一句,期待什么?请具体。
  • 我不知道你在问什么,但从问题名称来看,我想你可能想看看 While 循环?!
  • 第二个循环完全没用。删掉就写elif vowelnames in ('Bilal'...
  • 我想要的输出是:~~~哦,我可爱的朋友阿里! ,我希望你来参加我的毕业典礼哦,我可爱的朋友阿斯玛! ,我要你来参加我的毕业典礼~~~ 我要你来参加我的毕业典礼哦,我可爱的朋友阿姆娜! ,我希望你来参加我的毕业典礼哦,我可爱的朋友奥马尔! ,我希望你来参加我的毕业典礼 我希望你来参加我的毕业典礼

标签: python function loops nested iteration


【解决方案1】:

你必须使用“范围”

friends= ['Ali', 'Asma','Amna', 'Izma', 'Omer','Zahid','Bilal','Sarah']
for i in range(x): #Here instead of x you can give a number so that the loop will run 
                   #till that number
    for vowelnames in friends:
        if vowelnames in ('Ali','Asma','Izma','Omer'):
            print('Oh my lovely friend ' + vowelnames + '! ,I would like you to come 
                  on my graduation ceremony')
else:
    for cons in friends[:8]:
        if cons in ('Bilal','Sarah','Zahid'):
            print( cons + " I would like you to come on my graduation ceremony")

【讨论】:

  • 您正在另一个外部循环中运行完整的代码,这不是 OP 想要的(尽管不清楚他 想要什么
  • 好的,但如果他给出较低的值,循环将运行的次数更少,而不是那个“x”!正如你所说。 @Aryerez
  • 如果没有你的添加,他的代码只会运行一次。现在它将运行“X”次(并且每次都做同样的事情,因为他的代码内部没有任何变化与“X”相关)。我不知道有什么方法可以让循环运行的次数少于 1。
猜你喜欢
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 2016-07-06
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多