gpt4 book ai didi

python - 替换列表中的每个第二个元素

转载 作者:太空狗 更新时间:2023-10-30 01:01:18 24 4
gpt4 key购买 nike

我有一个二维列表:

[[5, 80, 2, 57, 5, 97], [2, 78, 2, 56, 6, 62], [5, 34, 3, 54, 6, 5, 2, 58, 5, 61, 5, 16]]

我需要从第一个元素开始,每隔一个元素将其更改为 0。所以它应该是这样的:

[[0, 80, 0, 57, 0, 97], [0, 78, 0, 56, 0, 62], [0, 34, 0, 54, 0, 5, 0, 58, 0, 61, 0, 16]]

我使用的算法:

for i in tempL: 
for j, item in enumerate(i):
if i.index(item) % 2 == 0:
print('change, index:'),
print(i.index(item))
i[j] = 0
else:
print('not change, index:'),
print(i.index(item))

但我得到的是:

change, index: 0
not change, index: 1
change, index: 2
not change, index: 3
change, index: 4
not change, index: 5
change, index: 0
not change, index: 1
change, index: 2
not change, index: 3
change, index: 4
not change, index: 5
change, index: 0
not change, index: 1
change, index: 2
not change, index: 3
change, index: 4
not change, index: 5
change, index: 6
not change, index: 7
not change, index: 5
not change, index: 9
not change, index: 5
not change, index: 11
[[0, 80, 0, 57, 0, 97], [0, 78, 0, 56, 0, 62], [0, 34, 0, 54, 0, 5, 0, 58, 5, 61, 5, 16]]

有些元素没有改变,这是因为(我添加了索引打印来查看)出于某种原因它认为这些元素的索引是 7 和 9。怎么回事啊,找bug找了这么久还是没找到。。

我仔细检查过,列表中没有多余的空格或任何内容。

最佳答案

好吧,这个任务应该是显而易见的。使用切片赋值!您需要分配一个半长的零数组。要创建一个,只需将单个元素数组乘以值:

for l in tempL: 
l[::2] = [0] * ((len(l)+1)/2)

或者使用 itertools 中的 repeat(不幸的是,对于小数组,这会慢两倍):

from itertools import repeat

for l in tempL:
l[::2] = repeat(0,(len(l)+1)/2)

关于python - 替换列表中的每个第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27461677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com