Python For 循环常用示例
格式
for {variable} in {some-sequence-type}:
{python-statements}
else:
{python-statements}
常见序列类型:lists,strings,tuples等
示例
Numbers循环
# list
>>> for i in [1, 2, 3, 4, 5]:
... print(i)
...
1
2
3
4
5
# 可以把list替换成tuple
>>> for i in (1, 2, 3, 4, 5):
... print(i)
...
1
2
3
4
5
Strings循环
>>> names = ['john', 'raj', 'lisa']
>>> for i in names:
... print(i)
...
john
raj
lisa
Range默认
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
Range(自定义起始和结束值)
>>> for i in range(1, 6):
... print(i)
...
1
2
3
4
5
Range(指定步长)
>>> for i in range(1, 6, 2): # 未指定,默认为1
... print(i)
...
1
3
5
Range(负值)
>>> for i in range(4, -5, -2):
... print(i)
...
4
2
0
-2
-4
Continue
>>> names = ['john', 'lisa', 'raj', 'lisa']
>>> for i in names:
... if i != 'lisa':
... continue # i不等于lisa则跳过本次循环
... print(i)
...
lisa
lisa
Break
>>> names = ['john', 'lisa', 'raj', 'lisa']
>>> for i in names:
... if i == 'raj':
... break # i等于raj则退出整个for循环。
... print(i)
...
john
lisa
有些场景可以使用return替换break,效果是一样的,见《Python Tricks: The BookA Buffet of Awesome Python Features》
For + Else
>>> names = ['john', 'lisa', 'raj', 'lisa']
>>> for i in names:
... print(i)
... else:
... print('--Done--')
...
john
lisa
raj
lisa
--Done--
for循环结束后,执行else语句
For + Break + Else
>>> names = ['john', 'lisa', 'raj', 'lisa']
>>> for i in names:
... if i == 'raj':
... break
... print(i)
... else: # 使用break将不会执行到else语句
... print('--Done--')
...
john
lisa
多重循环
>>> distros = ["centos", "redhat", "ubuntu"]
>>> arch = ["32-bit", "64-bit"]
>>> for i in distros:
... for j in arch:
... print('{} {}'.format(i, j))
... print('--------')
...
centos 32-bit
centos 64-bit
--------
redhat 32-bit
redhat 64-bit
--------
ubuntu 32-bit
ubuntu 64-bit
--------
Lists中的list
>>> multiple_state_lists = [ ["CA","NV","UT"], ["NJ","NY","DE"]]
>>> for state_list in multiple_state_lists:
... for state in state_list:
... print(state)
...
CA
NV
UT
NJ
NY
DE
Enumerate(输出索引)
>>> names = ['john', 'lisa', 'raj', 'lisa']
>>> for index, item in enumerate(names):
... print('{} {}'.format(index, item))
...
0 john
1 lisa
2 raj
3 lisa
Zip(多list使用)
>>> names = ['john', 'lisa', 'raj', 'lisa']
>>> ages = [28, 25, 31, 20]
>>> for item in zip(names, ages):
... print('{name}:{age}'.format(name=item[0], age=item[1]))
...
john:28
lisa:25
raj:31
lisa:20
Dict(items)
>>> peoples = {'john': 28, 'lisa': 25, 'raj': 31}
>>> for k, v in peoples.items():
... print('{name}:{age}'.format(name=k, age=v))
...
raj:31
john:28
lisa:25
推导式(list)
>>> ['Hi' for _ in range(5)]
['Hi', 'Hi', 'Hi', 'Hi', 'Hi']
推导式(dict)
>>> {i: i * 2 for i in range(5)}
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
推导式(生成器)
>>> [i for i in (i for i in range(5))]
[0, 1, 2, 3, 4]
推导式(if语句)
>>> [i for i in range(5) if i % 2]
[1, 3]