我有一个 Python 列表
list1 = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
有连续的 1 和 0 的“分组”。出于我的目的,我只对连续的 1 感兴趣。假设是否有一个单独的 1,例如
... 0, 0, 1, 0, 0 ...
我希望它变成 0。同样,如果只有成对的 1,这些也应该变成 0。例如
.... 0, 0, 1, 1, 0, 0...
应该变成
.... 0, 0, 0, 0, 0, 0...
但是连续或更高的“三胞胎”是可以的。
我考虑过通过字典来跟踪 1 的计数,但这感觉太复杂了。这个想法是遍历列表,跟踪列表中连续 1 的计数。但是,您如何“返回”并将 1 切换为 0?
counter_list = []
for i in list1:
if i == 1:
counter_list = counter_list + 1
if len(counter_list)==1 or len(counter_list)==2:
# now I don't know how to "go back" to change these elements into 0s
最佳答案
这是一个腐 eclipse ,然后是一个膨胀,计算机视觉中的常见操作:
>>> from scipy.ndimage.morphology import binary_dilation, binary_erosion
>>> print(list1)
[0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
>>> print(binary_dilation(binary_erosion(list1)).astype(int))
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
这两个操作的组合称为开:
>>> from scipy.ndimage.morphology import binary_opening
>>> print(binary_opening(list1).astype(int))
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
关于python - 什么是删除列表中双倍重复项但允许三元组/更大的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43104175/