# Python进阶篇-011. 数据处理基础函数（一）

\[toc]

### 一、创作声明

进阶篇是对基础篇的补充，这里面更多的是各种常用库、高级语法糖的教程，因此，进阶篇的内容会比较零碎。在创作过程中，同样会借助ChatGPT来辅助。

### 二、map函数

* 语法：`map(func, iterable)`
* 示例：

  ```python
  # 将列表中的每个元素都加1
  nums = [1, 2, 3, 4, 5]
  result = list(map(lambda x: x + 1, nums))
  print(result)  # 输出：[2, 3, 4, 5, 6]
  ```

### 三、flatMap函数

* 语法：`flatMap(func, iterable)`
* 示例：

  ```python
  # 将列表中的每个元素拆分成单个字符
  words = ['hello', 'world']
  result = list(flatMap(lambda x: list(x), words))
  print(result)  # 输出：['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
  ```

### 四、reduceByKey函数

* 语法：`reduceByKey(func, iterable)`
* 示例：

  ```python
  # 统计列表中每个元素的个数
  words = ['apple', 'banana', 'apple', 'orange', 'banana']
  result = reduceByKey(lambda x, y: x + y, words)
  print(result)  # 输出：{'apple': 2, 'banana': 2, 'orange': 1}
  ```

### 五、解释说明

以上示例中，`func`是一个函数，`iterable`是一个可迭代对象（如列表、元组等）。`map`函数将`func`应用于`iterable`中的每个元素，并返回一个新的可迭代对象。`flatMap`函数与`map`函数类似，但是会将`func`应用于`iterable`中的每个元素，并将结果展平为一个新的可迭代对象。`reduceByKey`函数将`func`应用于`iterable`中的每个元素，并按照键进行分组，最后返回一个字典，其中键是`iterable`中的元素，值是应用`func`后的结果。

### 六、写在最后

更多技术分享，点击传送门：<https://github.com/maxiaolu66/profile>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maxiaolu.gitbook.io/python/02-jin-jie-pian/python-jin-jie-pian-011.-shu-ju-chu-li-ji-chu-han-shu-yi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
