'looping a list and skip from another list
is there a better way to do this, this code is working but i feel like there is a better way to do it
mainlist = ['a','b','c','d','e','f','i','j','k']
skiplist = [4,6]
avilable=[j for j in range(len(mainlist)+len(skiplist)+1) if j not in skiplist]
i=avilable[0]
for letter in mainlist:
print (letter," is ",i)
i= avilable[avilable.index(i)+1]
result
a is 0
b is 1
c is 2
d is 3
e is 5
f is 7
i is 8
j is 9
k is 10
Solution 1:[1]
Since you've already worked out how to build available you could just zip the two:
mainlist = ['a','b','c','d','e','f','i','j','k']
skiplist = [4,6]
available= [j for j in range(len(mainlist)+len(skiplist)) if j not in skiplist]
for i, j in zip(mainlist, available):
print(f"{i} is {j}")
Another option might be to use a counter to build the values of j as you go:
mainlist = ['a','b','c','d','e','f','i','j','k']
skiplist = [4,6]
j = 0
for i in mainlist:
while j in skiplist:
j += 1
print(f"{i} is {j}")
j += 1
Yet another option would be to build a generator using something like itertools.count and filter:
from itertools import count
mainlist = ['a','b','c','d','e','f','i','j','k']
skiplist = [4,6]
available = filter(lambda j: j not in skiplist, count())
for i, j in zip(mainlist, available):
print(f"{i} is {j}")
Solution 2:[2]
You can use enumerate to get index and value same time. Single for loop is enough to solve problem.
mainlist = ['a','b','c','d','e','f','i','j','k']
skiplist = [4,6]
skipAmout = 0
for i, letter in enumerate(mainlist):
if i in skiplist:
skipAmout +=1
print (letter," is ",i+skipAmout)
Solution 3:[3]
mainlist = ['a','b','c','d','e','f','i','j','k']
skiplist = [4,6]
i=0
for letter in mainlist:
if i in skiplist:
i+=1
print (letter," is ",i)
i+=1
Getting rid of the unnecessary list makes it much simpler
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Tar?k Ramazan BA?O?LU |
| Solution 3 | MahMoud Hegab |
