Reputation: 95
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
I have the code like the above. I want to convert this while loop code to for loop. (Also, if possible, I want convert to list comprehension code) How can I do this? Thanks for your help.
Upvotes: 0
Views: 658
Reputation: 554
You can just replace your
num = 0
while num <= len(list_to):
By
for num in range(0, len(list_to)):
This way, your variable "num" would automatically take value 0
, then 1
, ... len(list_to)-1
Upvotes: 4
Reputation: 11
With For loop
for i in range(len(list_to)):
if list_to[i] in list_from:
save.append(from_dict[list_to[i]])
else:
save.append('')
Upvotes: 1