python输出列表中的第二个元素_python – 替换列表中的每个第二个元素

本文介绍了如何在Python中遍历二维列表并替换每个子列表的第二个元素为0。示例代码展示了一个算法,但遇到了问题,导致某些元素未被正确更改。问题在于对元素索引的判断有误,导致部分元素未被更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我有一个二维列表:

[[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还是找不到..

我仔细检查过,列表中没有多余的空格或任何东西.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值