0

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

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
4

4 回答 4

2

既然你已经想出了如何构建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.countand的东西构建生成器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}")
于 2022-02-20T20:18:13.387 回答
1

没有那个额外的列表:

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)
于 2022-02-20T20:20:49.073 回答
-1

您可以使用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)
于 2022-02-20T20:25:09.047 回答
-1
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

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

于 2022-02-20T20:51:46.867 回答