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

标签 python list

我有一个 L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4] 形式的列表,我想删除第三个索引,其中 1发生并将其替换为 0。我的代码是这样的,但这删除了我想要在我的列表中的 1(第一和第二)的先前索引。我的代码是这样的

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 提前致谢

最佳答案

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

寻找第n个索引

没有 builin 可以找到第 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]

使用列表理解

或者,如果您只想替换第 nth 次出现,但不关心它的实际索引,您可以使用列表理解和 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)

输出

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

关于python - 如何跳过数组中的特定索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50858477/

相关文章:

python - 如何链接多个脚本?

Python:按分隔符列表拆分字符串

r - 利用回收将不同长度的列表转换为数据帧的功能

Python:尝试反序列化文件中的多个 JSON 对象,每个对象跨越多个但间隔一致的行数

python - i = i + n 真的和 i += n 一样吗?

python - 列表理解以展平字典的字典

list - Prolog - 第一个列表是第二个列表的子列表,同时保持顺序?

c++ - 平台游戏(如马里奥兄弟)的碰撞不起作用

C# 列表属性初始化模式

list - 如何获取在 Scala 的列表中多次出现的所有元素的集合?