一、enumerate()函数
enumerate()函数用于将一个可遍历数据对象(列表、元组、字符串等)组合成一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中,其语法为:
enumerate(sequence , start)
参数:
sequence:可遍历数据对象(如:列表、元组、字符串等)
start:下标起始位置
返回值:
返回 enumerate(枚举) 对象,key为下标值,value为数据对象元素(即列表、元组、字符串中的元素)
例:
# 定义可遍历对象
sequence = ['a' , 'b' , 'c' , 'd']
str = "efgh"
# for循环遍历enumerate()函数,下标默认从0开始
for key , value in enumerate(sequence):
print(key , value)
print("---")
# for循环遍历enumerate()函数,下标默认从1开始
for key , value in enumerate(str , start = 1):
print(key , value)
执行结果:
0 a
1 b
2 c
3 d
---
1 e
2 f
3 g
4 h
二、字典(Dictionary) items()函数
Python中字典(Dictionary)的 items() 函数以列表的形式返回可遍历的(键, 值) 元组数组,语法格式为:
dict.items()
参数:
无
返回值:
以列表的方式返回可遍历的(键, 值) 元组数组
例:
# 定义字典
dict = {'Google': 'www.google.com',
'baidu': 'www.baidu.com',
'taobao': 'www.taobao.com' ,
"Apple":"www.apple.com"}
# for循环遍历dict.items()函数,输出(key , value)
# 当有两个参数时:
for key , value in dict.items():
# print(key + ":" + dict[key])
print(key + ":" + value)
print("------------------------------")
# 当仅有一个参数时返回(key , value)元组:
for key in dict.items():
print(key)
执行结果:
Google:www.google.com
baidu:www.baidu.com
taobao:www.taobao.com
Apple:www.apple.com
------------------------------
('Google', 'www.google.com')
('baidu', 'www.baidu.com')
('taobao', 'www.taobao.com')
('Apple', 'www.apple.com')
三、join()方法
join() 方法可将序列中的元素以指定的字符连接后生成一个新的字符串,语法为:str.join(sequence)
参数:
str:指定连接元素序列的字符
sequence:要连接的元素序列
例:
sequence = ('床' , '前' , '明' , '月' , '光')
str = "*"
print(str.join(sequence))
执行结果:
床*前*明*月*光