列表理解并遍历列表

时间:2016-01-26 01:03:23

标签: python python-3.x list-comprehension

[k for k in range (1,42) if k%2 != 0]

输出:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41]

现在,我想要:

[-1, 3, -5, 7, -9, 11, -13, 15, -17, 19, -21, 23, -25, 27, -29, 31, -33, 35, -37, 39, -41]

所以我试过了:

def test(N):
    k = []
    for i in range (1,N+1):
        if(i%2 != 0):
            k.append(i)
    for b in k[::2]:       <--- it changes the value but doesn't update the list
        b = -b
    return k
test(43)

有关如何解决此问题的任何想法或建议?或者另一个问题是,如何在将元素更新为负值时遍历列表中的偶数编号索引

3 个答案:

答案 0 :(得分:2)

这有效:

numbers = (k for k in range(1, 42) if k%2 != 0)
[x * [-1, 1][n % 2] for n, x in enumerate(numbers)]

输出:

[-1, 3, -5, 7, -9, 11, -13, 15, -17, 19, -21, 23, -25, 27, -29, 31, -33, 35, -37, 39, -41]

效果

使用模数的方法比Malik Brahimi在评论中建议的交替系列快一点:

%%timeit
numbers = (k for k in range(1, 420000) if k%2 != 0)
[x * (-1)**(n + 1) for n, x in enumerate(numbers)]
1 loops, best of 3: 263 ms per loop

%%timeit
numbers = (k for k in range(1, 420000) if k%2 != 0)
[x * [-1, 1][n % 2] for n, x in enumerate(numbers)]
1 loops, best of 3: 210 ms per loop

答案 1 :(得分:1)

[k if k%4==3 else -k for k in range (1,42) if k%2 != 0]

答案 2 :(得分:1)

b是对存储在k中的(不可变)整数的引用。通过将b更新为等于-b,您不会修改列表,只需将int 2对象更改为b-referecnes,就可以将int 2对象更改为int -2对象。在构建列表时,你可能会更好地做出否定:

def test(N):
    k = []
    for i in range (1,N+1, 2): # i increases in steps of 2
        if i % 4 == 1:
            i = -i
        k.append(i)
    return k

test(43)