简体   繁体   English

在python中对0和1进行分组

[英]Grouping 0s and 1s in python

I have an array of zeros and ones like [0,0,0,1,1,1,0,0,0,1,1] .我有一个像[0,0,0,1,1,1,0,0,0,1,1]这样的零和一个数组。 How to write a program to save neighboring 0's and 1's in different arrays.如何编写程序将相邻的 0 和 1 保存在不同的数组中。

Eg [0,0,0,1,1,1,0,0,0,1,1] giving [0,0,0],[1,1,1],[0,0,0],[1,1] .例如[0,0,0,1,1,1,0,0,0,1,1]给出[0,0,0],[1,1,1],[0,0,0],[1,1]

You can group them with itertools.groupby , like this你可以用itertools.groupby它们分组,就像这样

>>> data = [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1]
>>> from itertools import groupby
>>> [list(group) for item, group in groupby(data)]
[[0, 0, 0], [1, 1, 1], [0, 0, 0], [1, 1]]

The result of groupby , will be a tuple of actual item and an iterator which gives the grouped items. groupby的结果将是一个实际项目的元组和一个提供分组项目的迭代器。 We just convert the grouped items to a list, with list(group) .我们只是将分组的项目转换为列表,使用list(group)


As per the comments,根据评论,

>>> data = [1, 2, 1, 3, 4, 5, 6, 7, 1, 2, 3]
>>> flag = [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1]

Create a generator which will give the values multiplied,创建一个生成器,它将使值相乘,

>>> gen = (d * v for d, v in zip(data, flag))

Now, group based on the result of calling bool on each of the numbers.现在,根据对每个数字调用bool的结果进行分组。 So, if the bool is called on 0 , it will give False , otherwise True .因此,如果bool0上被调用,它将给出False ,否则为True

>>> [list(g) for _, g in groupby(gen, key=bool)]
[[0, 0, 0], [3, 4, 5], [0, 0, 0], [2, 3]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM