from itertools import count
def get_nth_index(lst, item, n):
c = count(1)
return next((i for i, x in enumerate(lst) if x == item and next(c) == n), None)
a = [9,8,2,3,8,3,5]
indx = get_nth_index(a, 8, 2)
if indx is not None:
del a[indx]
print(a)
# [9, 8, 2, 3, 3, 5]
remove()从列表中删除与指定值匹配的第一项。要删除第二个引用,可以使用del而不是移除。The代码应该很容易理解,我使用count来跟踪item的出现次数,当count变为2时,元素被删除。在
我不清楚为什么这个特定的任务需要一个循环:
下面是一种使用
itertools.count
与生成器一起使用的方法:相关问题 更多 >
编程相关推荐