3

I have a list of booleans. I also have a list of start and end indices. In my list of booleans, I want each value to be True unless it lies in one of the slices defined in the list of indices. What I have written feels very clunky, any suggestions for making it nicer?

bools = [True] * 15
events = [(3, 5), (11, 16)]
for e in events:
    bools[e[0]:e[1]] = [False for x in range(*e)] 

specifically, I don't like the [False for x in range(*e)] part. If I start messing around with the slices, the range(*e) starts to get messy, e.g.:

    bools[e[0]:e[1]+2] = [False for x in range(e[0], e[1]+2)]

What would be really nice is if there were a syntax to make every value in a list/slice take the same value, e.g.

    bools[e[0]:e[1]+2] = False

But this, obviously, is not correct syntax. Any ideas?

4

3 回答 3

1
from itertools import repeat
for e in events:
    bools[e[0]: e[1]] = repeat(False, e[1] - e[0]) 
于 2013-11-12T02:27:11.350 回答
0

有兴趣使用 numpy 吗?

bools[e[0]:e[1]+2] = False

在 numpy 中工作。你也可以直接创建你自己的切片对象,让你做这样的事情

slices = [np.s_[3:6], np.s_[11:17]]
for s in slices:
    bools[s] = False

使用 s_ 完全支持切片语法(步长、从列表末尾索引、省略号),而不仅仅是枚举范围

于 2013-11-12T02:09:31.537 回答
0

我会这样做:

events = [(3, 5), (11, 16)]
bools = [True] * 16
for start, end in events:
    for index in range(start, end):
        bools[index] = False
于 2013-11-12T02:22:22.077 回答