python for循环
格式:
for iterating_var in sequence:
statements(s)
########################################
可多层嵌套
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
for iterating_var in sequence:
...
statements(s)
常用函数
enumerate()
对于字典,返回key的下标和key本身的值
info = {'name':'lijiang', 'age':0, 'a':100}
print(info)
for key, valuel in enumerate(info):
print(key, valuel)
执行
C:\Python27\python.exe D:/Python/type-of-data.py
{'a': 100, 'age': 0, 'name': 'lijiang'}
(0, 'a')
(1, 'age')
(2, 'name')
Process finished with exit code 0
############################################################################
对于更序列(列表、元组或字符串),返回下标及下标对应的值,以字符串为例:
name = 'lijiang'
for key, valuel in enumerate(name):
print(key, valuel)
执行
C:\Python27\python.exe D:/Python/type-of-data.py
(0, 'l')
(1, 'i')
(2, 'j')
(3, 'i')
(4, 'a')
(5, 'n')
(6, 'g')
Process finished with exit code 0
iteritems()
info = {'name':'lijiang', 'age':0, 'a':100}
for key, valuel in info.iteritems():
print(key, valuel)
执行:
C:\Python27\python.exe D:/Python/type-of-data.py
('a', 100)
('age', 0)
('name', 'lijiang')
Process finished with exit code 0
range() 和 xrange()
print(range(10))
print(type(range(10)))
print(xrange(10))
print(type(xrange(10)))
执行
C:\Python27\python.exe D:/Python/type-of-data.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<type 'list'>
xrange(10)
<type 'xrange'>
Process finished with exit code 0