Python 字典(Dictionary) items()方法+enumerate() 函数

Python 字典(Dictionary) items()方法

描述

Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

语法

items()方法语法:

dict.items()

参数

NA。

返回值

返回可遍历的(键, 值) 元组数组。

实例

以下实例展示了 items()函数的使用方法:

实例(Python 2.0+)
# coding=utf-8
 dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}
 print "字典值 : %s" %  dict.items()
 # 遍历字典列表
for key,values in  dict.items():
    print key,values

以上实例输出结果为:

字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com

items() 方法的遍历:items() 方法把字典中每对 key 和 value 组成一个元组,并把这些元组放在列表中返回。

d = {'one': 1, 'two': 2, 'three': 3}
>>> d.items()
dict_items([('one', 1), ('two', 2), ('three', 3)])
>>> type(d.items())
<class 'dict_items'>

>>> for key,value in d.items():#当两个参数时
    print(key + ':' + str(value))
one:1
two:2
three:3

>>> for i in d.items():#当参数只有一个时
    print(i)
('one', 1)
('two', 2)
('three', 3)

enumerate() 函数

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
以下是 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')]

普通的 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

巧妙利用 enumerate() 批量修改列表内的元素:

list1 = ['01','02','03']
unit_element = '1'
for i,element in enumerate(list1):
  list1[i] = unit_element + element
print(list1)

输出结果:

['101', '102', '103']

或者

list1 = ['01','02','03']
list1=["1"+str for str in list1]
print(list1)

输出结果:

['101', '102', '103']

版权声明:本文为qq_43906485原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。