WordPress网站建设宣传图片

Python enumerate() 函数,Python将列表转换为索引:元素的字典

释放双眼,带上耳机,听听看~!

Python将列表转换为索引:元素的字典可以使用Python enumerate() 函数,enumerate() 函数是Python中的一个内置函数。

enumerate() 函数

介绍

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

Python 2.3. 以上版本可用,2.6 添加 start 参数。

enumerate()函数语法

以下是 enumerate() 方法的语法:

enumerate(sequence, [start=0])

参数

  • sequence — 一个序列、迭代器或其他支持迭代对象。
  • start — 下标起始位置的值。

返回值

返回 enumerate(枚举) 对象。

实例

以下展示了使用 enumerate() 方法的实例:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))  # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

返回值是一个enumerate(枚举) 对象。

citys = ["jinan", "qingdao", "yantai", "zibo"]
print(enumerate(citys))

输出结果

<enumerate object at 0x000001BC38DC3440>

默认每个元素是一个元组 第一个值是索引 第二个值是元素

citys = ["jinan", "qingdao", "yantai", "zibo"]
for city in enumerate(citys):
    print(city)

输出结果

(0, 'jinan')
(1, 'qingdao')
(2, 'yantai')
(3, 'zibo')

普通的 for 循环

>>> i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
...     print i, seq[i]
...     i += 1
...
0 one
1 two
2 three

for 循环使用 enumerate

>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
...
0 one
1 two
2 three

将列表转换为索引:元素的字典

示例代码

# -*- coding: utf-8 -*-
test_list = ['a', 'b', 'c']
test_dict = dict()

# 可以直接通过dict进行转换
# test_dict = dict(enumerate(test_list))

# for循环
for e_index, element in enumerate(test_list):
    print(e_index, element)
    test_dict[e_index] = element

print(test_dict)

输出结果

0 a
1 b
2 c
{0: 'a', 1: 'b', 2: 'c'}
enumerate

相关资料

Python字典按照值(value)的大小进行排序方法

Python enumerate() 函数

Python 内置函数

给TA打赏
共{{data.count}}人
人已打赏
Python内置模块Python字典Python笔记

Python 将字符串转为字典

2023-9-15 16:11:28

Python RequestsPython异常处理Python爬虫Python笔记

Python requests 异常InsecureRequestWarning: Unverified HTTPS request is being made to host '***domain'. Adding certificate verification is strongly advised. See...解决

2023-12-7 12:04:41

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
展开目录