反转python布尔列表中的边值

时间:2018-07-30 15:21:28

标签: python

我有一个类似布尔值的列表

l = [False, False, False, True, True, True, False, False, True, False, False]

,并且想要反转False之类的每个边值

[True, True, True, True, True, True, False, False, True, True, True]

实现这一目标的最Python方式是什么?

4 个答案:

答案 0 :(得分:5)

可能有一些聪明的单行解决方案,但是在有人提出之前,这是一种老式的迭代方法:

C

结果:

seq = [False, False, False, True, True, True, False, False, True, False, False]

for i in range(len(seq)):
    if seq[i]:
        break
    seq[i] = True

for i in range(len(seq)-1, -1, -1):
    if seq[i]:
        break
    seq[i] = True

print(seq)

答案 1 :(得分:2)

您可以使用几个生成器表达式,然后使用NumPy进行矢量化切片。

这个想法是从列表的开头和结尾分别计算第一个索引,其中值是True。然后使用有效的NumPy切片来更新相关元素。

L = [False, False, False, True, True, True, False, False, True, False, False]

idx1 = next(i for i, j in enumerate(L) if j)
idx2 = next(i for i, j in enumerate(L[::-1]) if j)

print(idx1, idx2)  # 3 2

import numpy as np

A = np.array(L)
A[:idx1] = True
A[len(A)-idx2:] = True

print(A)

array([ True,  True,  True,  True,  True,  True, False, False,  True,
        True,  True], dtype=bool)

答案 2 :(得分:0)

我建议您使用以下简单代码:

myList = [False, False, False, True, True, True, False, False, True, False, False]

tempList = myList[:]

# Iterate from the beginning (and invert) until the element differs from the first one
for i,v in enumerate(tempList):
    if v == tempList[0]: myList[i] = not v
    else:                break

# Iterate from the end (and invert) until the element differs from the last one
for i,v in reversed(list(enumerate(tempList))):
    if v == tempList[-1]: myList[i] = not v
    else:                 break

print(myList)
# [True, True, True, True, True, True, False, False, True, True, True]

答案 3 :(得分:0)

根据其他答案的逻辑,这是使用numpy.where的解决方案。

import numpy as np

l = [False, False, False, True, True, True, False, False, True, False, False]

l = np.array(l)
ind = np.where(l)[0]
first, last = ind[0], ind[-1]

l[:first] = True
l[last + 1:] = True

print(l)

这是受NPEhttps://stackoverflow.com/a/9537766/2611995的回答的启发。