enumerate 是 Python 中用于同时获得可迭代对象的元素和它们的索引的内置函数。这对于在循环中需要迭代对象的值以及它们的位置时非常有用。
以下是 enumerate 的基本语法:for index, value in enumerate(iterable):
# index 是元素的索引。value 是可迭代对象的元素。
- import pandas as pd
- import numpy as np
-
- # 创建一个示例DataFrame
- data = {'A': [7, 2, 3], 'B': [3, 5, 6], 'C': [0, 8, 9]}
- df = pd.DataFrame(data)
-
- # 获取行数和列数
- num_rows, num_columns = df.shape
-
- # 打印结果
- print("行数:", num_rows)
- print("列数:", num_columns)
-
-
- # # 使用.values.T 将DataFrame按'列'转换为NumPy数组
- # numpy_array = df.T.values
-
- # # 打印结果
- # print(numpy_array)
-
-
- # 将DataFrame按列转换为numpy数组,enumerate遍历DataFrame的'列'并逐一填充NumPy数组
- numpy_data = np.zeros((num_rows,num_columns))
- col = df.columns
- for i,j in enumerate(col):
- numpy_data[i]=df[j]
- print(numpy_data)
- fruits = ['apple', 'banana', 'cherry']
- for index, fruit in enumerate(fruits):
- print(f"Index {index}: {fruit}")
- fruits = ['apple', 'banana', 'cherry']
-
- # 使用 enumerate 查找 'banana' 的位置
- for index, fruit in enumerate(fruits):
- if fruit == 'banana':
- print(f"'banana' 在位置 {index}")
- document = "This is a sample document containing some keywords."
-
- keywords = ['sample', 'keywords']
-
- # 使用 enumerate 记录关键词的位置
- for index, word in enumerate(document.split()):
- if word in keywords:
- print(f"'{word}' 在位置 {index}")
迭代 (Iteration):
for 循环来完成,但它的目的是遍历容器中的元素而不是简单地重复操作。示例使用 for 循环进行迭代:
- fruits = ['apple', 'banana', 'cherry']
- for fruit in fruits:
- print(fruit)
双重 for 循环(也称为嵌套循环)是一种在循环中嵌套另一个循环的编程结构。它通常用于遍历多维的数据结构,如嵌套列表或矩阵。
- matrix = [
- [1, 2, 3],
- [4, 5, 6],
- [7, 8, 9]
- ]
-
- # 使用双重循环遍历二维列表
- for row in matrix:
- for element in row:
- print(element)