# 创建Python的For循环

2016年12月1日 / 147次阅读
Python

``````>>> for i in (1,2,3): # tuple
...    i
...
1
2
3
>>> for s in ('1','2','3'): #tuple and string
...     s
...
'1'
'2'
'3'
>>> for s in ('1','2','3','aaa'):
...     s
...
'1'
'2'
'3'
'aaa'
>>>
>>> for s in ['1','2','3','aaa']: # list is also ok
...     s
...
'1'
'2'
'3'
'aaa'
>>> for s in '12345': # a string,great
...     s
...
'1'
'2'
'3'
'4'
'5'
>>> for x in range(10): # range builtin
...     x
...
0
1
2
3
4
5
6
7
8
9
>>>``````

``````>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
robin the brave``````

``````>>>
>>> for i,v in enumerate(se1):
...     print(i,v)
...
0 1.2
1 3
2 4
3 5
>>> se1
{1.2, 3, 4, 5}
>>>``````

2018-09-27：

``````words = ['cat', 'window', 'defenestrate']
for w in words:
if len(w) > 6:
words.insert(0, w)  # words has been changed, dead loop.``````

``````words = ['cat', 'window', 'defenestrate']
for w in words[:]:  # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)``````

for循环在words[:]上进行，循环内对words进行改变。

``````words = ['cat', 'window', 'defenestrate']
for i in range(len(words)):
if len(words[i]) > 6:
words.insert(0, words[i])``````

### 留言区

《创建Python的For循环》有7条留言

• 麦新杰

Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. []

• 麦新杰

for后面接多个变量时：

``````>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
...
1 1
2 4
3 9``````
[]

• 麦新杰

for ... in ... 只要是iterable object都可以。 []

• 麦新杰

默认情况下，dict迭代的是key。如果要迭代value，可以用for value in d.values()，如果要同时迭代key和value，可以用for k, v in d.items()。 []

• 麦新杰

遍历dict，默认是key：

``````>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
...     print(key)
...
a
c
b``````
[]

• builtin里面有函数，有class，有异常；for in 后面接的是一个object。 []

Ctrl+D 收藏本页