如何跳过数组中的特定索引?

时间:2018-06-14 13:16:16

标签: python list

我有一个L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]形式的列表,我想删除发生1的第三个索引,并将其替换为0.我的代码就是这个,但这会删除以前的索引1(第1和第2也)我想在我的名单中。我的代码就是这个

counter=0
index = 2
L = list([1, 2, 3, 4, 1, 2, 1, 3, 0, 4])
print("Value before is\n", L)
for i in range(len(L)):
    y=L.index(1)
    print(y)
    if(counter==index):
        L[y]=0
        break
    else:
        counter=counter+1
        L[y]
        print("Value of list in else\n",L)
        print("Value of counter\n",counter)

print("After the value is\n",L)

因此输出为

 [2, 3, 4, 2, 0, 3, 0, 4]

但我希望它为

L = [1, 2, 3, 4, 1, 2, 0, 3, 0, 4]

并记住我不会直接给出我想要更改的索引 所以我可以做L[7]=0 提前致谢

3 个答案:

答案 0 :(得分:3)

使用enumerate

<强>演示:

index = 2
value = 1
c = 0
L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]

for i, v in enumerate(L):
    if v == value:
        if c == index:
            L[i] = 0
            break
        else:
            c+=1
print( L )

<强>输出:

[1, 2, 3, 4, 1, 2, 0, 3, 0, 4]

答案 1 :(得分:3)

您的算法存在一些问题,但归结为:通过y = L.index(1),您可以找到1出现的第一个索引。因此,通过执行L[y] = 0,您所能做的就是更新1的第一次出现。

查找第n个索引

找不到 nth 外观没有构建,因此您必须编写它。

为了与list.index保持一致,我发现以下index函数在找不到该项时会引发ValueError

代码

def index(lst, obj, n=1):
    count = 0
    for index, item in enumerate(lst):
        if item == obj:
            count += 1
        if count == n:
            return index
    raise ValueError('{} is not in list at least {} times'.format(obj, n))

L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]

index = index(L, 1, n=3)

L[index] = 0

print(L)

输出

[1, 2, 3, 4, 1, 2, 0, 3, 0, 4]

使用list-comprehension

或者,如果您要做的只是替换 nth 出现,但不关心其实际索引,您可以生成一个包含列表推导和{{1}的新列表对象。

代码

itertools.count

输出

from itertools import count

def replace(lst, obj, repl, n=1):
    counter = count(1)
    return [repl if x == obj and next(counter) == n else x for x in lst]


L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]

new_list = replace(L, 1, 0, n=3)
print(new_list)

答案 2 :(得分:1)

您可以设置一个名为timesOccured的计数器变量,用于列表中出现整数1的次数。

timesOccured == 3 and L[i] == 1后,您可以像L[i]那样交换0的值,如下所示:

if timesOccured == 3 and L[i] == 1:
    L[i] = 0

我还建议删除counter变量,除非你的程序的另一部分需要它。 range中的for i in range(L)函数返回一个包含L所有索引的列表。在这种情况下,range(L)会返回[0,1,2,3,4,5,6,7,8,9]。然后for循环遍历此列表,在i中分配当前迭代索引中存储的当前值。