Python内置函数enumerate操作可迭代对象及for迭代

enumerate 是 Python 中用于同时获得可迭代对象的元素和它们的索引的内置函数。这对于在循环中需要迭代对象的值以及它们的位置时非常有用。

以下是 enumerate 的基本语法:for index, value in enumerate(iterable):

index 是元素的索引。value 是可迭代对象的元素。

python 复制代码
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)
python 复制代码
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
python 复制代码
fruits = ['apple', 'banana', 'cherry']

# 使用 enumerate 查找 'banana' 的位置
for index, fruit in enumerate(fruits):
    if fruit == 'banana':
        print(f"'banana' 在位置 {index}")
python 复制代码
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 循环进行迭代:

python 复制代码
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

双重 for 循环(也称为嵌套循环)是一种在循环中嵌套另一个循环的编程结构。它通常用于遍历多维的数据结构,如嵌套列表或矩阵。

python 复制代码
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# 使用双重循环遍历二维列表
for row in matrix:
    for element in row:
        print(element)
相关推荐
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健2 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers