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)
相关推荐
怕浪猫8 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
高洁018 小时前
具身智能中的世界模型训练
人工智能·python·深度学习·机器学习·transformer
无线通信科研笔记8 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
朝朝辞暮i8 小时前
VLA 系统学习第 1 课:VLA 到底在干什么?
人工智能·python·计算机视觉·vla
2601_962885729 小时前
如何用 Python 自动识别股票的支撑位与压力位?
开发语言·python
爱吃奥利奥_wen9 小时前
面向对象三板斧:封装、继承、多态,到底在“装“什么、“承“什么、“变“什么?
开发语言·经验分享·c#
北冥有鱼被烹9 小时前
VCSEL全景解析:与光模块NPO CPO的关系、市场量化分析与产业链影响
python
我可能是个假开发9 小时前
FTP Unicode 文件名导致 `550` 的问题分析与解决方案
java·开发语言·spring
caoerzhong10 小时前
中小企业上 WMS 该先上哪几块:JeeWMS 开源 Java 仓库管理系统的分批上线清单
java·python·开源
正在走向自律10 小时前
AI数据分析与可视化:从基础到应用实践
服务器·人工智能·python·机器学习·数据分析·pandas