【发布时间】:2015-02-12 05:29:21
【问题描述】:
我有一个二维列表:
[[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]]
有些元素没有改变,这是因为(我添加了 index print 来查看)它认为这些元素的索引是 7 和 9 出于某种原因。怎么回事,因为找了这么久的bug还是找不到..
我仔细检查了,列表中没有多余的空格或任何内容。
【问题讨论】:
-
你为什么使用
i.index?你不是说j吗?
标签: python