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
CodePudding user response:
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}")
CodePudding user response:
Without that extra list:
mainlist = ['a','b','c','d','e','f','i','j','k']
skiplist = [4,6]
i = 0
for letter in mainlist:
while i in skiplist:
i = 1
print(letter, ' is ', i)
i = 1
Or a fancy itertools
solution, also using a set instead of the list, which would be more efficient if the skiplist were large:
from itertools import count, filterfalse
mainlist = ['a','b','c','d','e','f','i','j','k']
skiplist = [4,6]
numbers = filterfalse(set(skiplist).__contains__, count())
for letter, number in zip(mainlist, numbers):
print(letter, ' is ', number)
CodePudding user response:
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)
CodePudding user response:
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