循环列表并从另一个列表中跳过

looping a list and skip from another list

有没有更好的方法来做到这一点,这段代码有效,但我觉得有更好的方法来做到这一点

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

既然你已经知道如何构建 available 你可以 zip 两个:

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}")

另一种选择可能是使用计数器来构建 j 的值:

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

另一种选择是使用 itertools.countfilter:

之类的东西构建生成器
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}")

没有那个额外的列表:

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

或者花哨的 itertools 解决方案,也使用集合而不是列表,如果跳过列表很大,效率会更高:

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)

您可以使用enumerate同时获取索引和值。一个for循环足以解决问题

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)
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

摆脱不必要的列表使它变得更简单