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)
相关推荐
weixin_468466853 分钟前
Scrapling 高效网络爬虫实战指南
爬虫·python·编程·scrapling
yubo05095 分钟前
计算机视觉第十课:摄像头实时 颜色 + 形状 识别
python·opencv·计算机视觉
眠りたいです5 分钟前
现代C++:C++17中的新语言特性
开发语言·c++·c++17
Dxy12393102165 分钟前
Django 三种 ENGINE 的区别
python·django·sqlite
Wang ruoxi6 分钟前
Pygame 小游戏——记忆方格
python·pygame
一只旭宝7 分钟前
【C++入门精讲17】序列容器
开发语言·c++
Demon1_Coder8 分钟前
Day1-SpringAI-1.0.0版本
java·开发语言·前端
shuaiqinke8 分钟前
[Windows] 屏幕亮度调节工具
python
本地化文档12 分钟前
sphinxcontrib-rust-docs-l10n
python·rust·github·gitcode·sphinx
麻雀飞吧12 分钟前
2026年期货量化行情订阅层设计:主流平台Quote、K线与Tick取舍
python