【问题标题】:How to convert while loop to for loop in python?如何在python中将while循环转换为for循环?
【发布时间】:2020-12-17 11:20:40
【问题描述】:
list_from=[1,2,3,4,5,6,7,8,9,10]
list_from2=[a,b,c,d,e,f,g,h,i,j]
from_dict={list_from[i]:list_from2[i] for i in range(len(list_from2))}
list_to = [1,2,5,10]
save=[]
num=0
while num<=len(list_to):
    try:
        if list_to[num] in list_from:
            save.append(from_dict[list_to[num]])
        else:
            save.append('')
       num+=1
   except:
        break

我有上面的代码。我想将此 while 循环代码转换为 for 循环。 (另外,如果可能的话,我想转换为列表理解代码) 我怎样才能做到这一点? 感谢您的帮助。

【问题讨论】:

  • 我想我的代码有误。似乎空列表“保存”输入两次。对此感到抱歉。
  • 对于 list_from 中的数字
  • from_dict = dict(zip(list_from, list_from2)) 会更简单。
  • save = [from_dict.get(x, '') for x in list_to]一样。

标签: python list for-loop while-loop


【解决方案1】:

你可以替换你的

num = 0
while num <= len(list_to):

for num in range(0, len(list_to)):

这样,你的变量“num”会自动取值0,然后是1,...len(list_to)-1

【讨论】:

    【解决方案2】:

    带 For 循环

    for i in range(len(list_to)):
        if list_to[i] in list_from:
            save.append(from_dict[list_to[i]])
        else:
            save.append('')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      • 2018-02-22
      • 2017-04-26
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多