python groupby
时间: 2023-08-27 18:07:02 浏览: 92
Python中的groupby分组功能的实例代码
The `groupby` function in Python is used to group data based on some specific criteria. It is a part of the `itertools` module and is used to group the elements of an iterable based on a key function. The key function is used to determine the grouping of the elements.
The syntax of the `groupby` function is as follows:
```python
itertools.groupby(iterable, key=None)
```
Here, `iterable` is the iterable object that needs to be grouped, and `key` is a function that is used to determine the grouping. If `key` is not specified or `None`, then the elements of the iterable will be grouped based on their identity.
The `groupby` function returns a generator object that yields tuples containing the group key and the elements of the group.
Example:
```python
import itertools
data = [1, 2, 3, 4, 5, 6]
groups = itertools.groupby(data, lambda x: x % 2)
for key, group in groups:
print(key, list(group))
```
Output:
```
1 [1, 3, 5]
0 [2, 4, 6]
```
In this example, we have used the `groupby` function to group the elements of the `data` list based on whether they are even or odd. The lambda function `lambda x: x % 2` is used as the key function to determine the grouping. The output shows that the elements with odd values are grouped together, and the elements with even values are grouped together.
阅读全文