替换列表中的每个第2个元素

时间:2014-12-13 17:31:31

标签: python

我有一个二维列表:

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

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

4 个答案:

答案 0 :(得分:3)

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

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)

答案 1 :(得分:2)

我认为你的算法是正确的。你刚刚犯了一个逻辑错误。通过使用i.index,您每次都会在内部列表中搜索该值。这不仅昂贵,而且对重复值很敏感。

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

答案 2 :(得分:1)

作为一种更加pythonic的方式你可以使用列表理解:

>>> l=[[5, 80, 2, 57, 5, 97], [2, 78, 2, 56, 6, 62], [5, 34, 3, 54, 6, 5, 2, 58, 5, 61, 5, 16]]
>>> l=[[t if k%2 else 0 for k,t in enumerate(i)] for i in l]
>>> l
[[0, 80, 0, 57, 0, 97], [0, 78, 0, 56, 0, 62], [0, 34, 0, 54, 0, 5, 0, 58, 0, 61, 0, 16]]

答案 3 :(得分:0)

加上我的两分钱:

使用模运算符

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

for i,n in enumerate(mylist):
    for j,m in enumerate(n):
        if j % 2 == 0:
            mylist[i][j] = 0

print mylist

输出:

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