一、enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中
基本语法:enumerate(sequence, [start=0])
参数:
sequence – 一个序列、迭代器或其他支持迭代对象。
start – 下标起始位置。
如:
列表:
text=[‘a’,1,‘boy’,‘girl’]
print list(enumerate(text))
[(0, ‘a’), (1, 1), (2, ‘boy’), (3, ‘girl’)]
text=[‘a’,1,‘boy’,‘girl’]
print list(enumerate(text,start=1))#下标从1开始
[(1, ‘a’), (2, 1), (3, ‘boy’), (4, ‘girl’)]
元组:
text=(‘a’,1,‘boy’,‘girl’)
print list(enumerate(text))
[(0, ‘a’), (1, 1), (2, ‘boy’), (3, ‘girl’)]
text=(‘a’,1,‘boy’,‘girl’)
print list(enumerate(text,start=1))#下标从1开始
[(1, ‘a’), (2, 1), (3, ‘boy’), (4, ‘girl’)]
字符串:
text=‘hello’
print list(enumerate(text,start=1))
[(1, ‘h’), (2, ‘e’), (3, ‘l’), (4, ‘l’), (5, ‘o’)]
字典:
text={‘boy’:‘xiao’,‘girl’:2,‘twice’:‘lisa’}
print list(enumerate(text))
输出:
[(0, ‘boy’), (1, ‘girl’), (2, ‘twice’)]
普通for循环,举例子:
text=[1,2,‘boy’,‘girl’]
i=0
for elemeng in text:
print i,text[i]
i+=1
输出:
0 1
1 2
2 boy
3 girl
for 循环使用 enumerate
text=[1,2,‘boy’,‘girl’]
for i,element in enumerate(text):
print i,element
print enumerate(text)
输出:
0 1
1 2
2 boy
3 girl
text=[1,2,‘boy’,‘girl’]
for i,element in list(enumerate(text)):
print i,element
print enumerate(text)
输出:
0 1
1 2
2 boy
3 girl
二、items()属于字典中的函数–字典转为列表即返回字典中所有键值对
d = {“one”:1,“two”:2,“three”:3}
print(d.items(),type(d.items()))
会输出:([(‘three’, 3), (‘two’, 2), (‘one’, 1)],
text={‘boy’:‘xiao’,‘girl’:2,‘twice’:‘lisa’}
print text.items()
输出:[(‘boy’, ‘xiao’), (‘girl’, 2), (‘twice’, ‘lisa’)]
d = {‘one’:‘xiao’,‘two’:‘zhi’,‘three’:1}
print d.items()
for key, value in d.items():
print key, value
输出:
[(‘three’, 1), (‘two’, ‘zhi’), (‘one’, ‘xiao’)]
three 1
two zhi
one xiao
d = {‘one’:‘xiao’,‘two’:‘zhi’,‘three’:1}
print d.items()
for key, value in d.items():
print [key, value]
输出:
[(‘three’, 1), (‘two’, ‘zhi’), (‘one’, ‘xiao’)]
[‘three’, 1]
[‘two’, ‘zhi’]
[‘one’, ‘xiao’]