全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
1322 1
2015-05-07
while loops:

while test:
    statements
else:
    statements

the following can be inside the loop:

break: jumps out of the closest enclosing loop
continue: jumps to the top of the closest enclosing loop
pass: do nothing: empty statement placeholder
else: runs if and only if the loop is exited normally (without hitting break)

for target in object:
    statements
else:
    statements

any sequence works in a for, it is a generic tool. Loop target itself can be tuple of targets.




二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2015-5-7 23:29:53
counter loops: range(-5,3)

len(list)

parallel traversals: zip and map

L1=[1,2,3,4]
L2 = [5,6,7,8]

zip(L1, L2)
[(1, 5), (2, 6), (3, 7), (4, 8)]

for (x,y) in zip(L1,L2):
    print x, y, '--', x+y

zip truncates result tuples at the length of the shortest sequence when the
argument lengths differ.

>>> S1 = 'abc'
>>> S2 = 'xyz123'
>>> map(None, S1, S2) # 2.X only: pads to len(longest)
[('a', 'x'), ('b', 'y'), ('c', 'z'), (None, '1'), (None, '2'), (None,'3')]

>>> list(map(ord, 'spam'))
[115, 112, 97, 109]

works the same as
This works the same as the following loop statement, but map is often quicker:

>>> res = []
>>> for c in 'spam': res.append(ord(c))
>>> res
[115, 112, 97, 109]

>>> keys = ['spam', 'eggs', 'toast']
>>> vals = [1, 3, 5]

>>> D = {}
>>> for (k, v) in zip(keys, vals): D[k] = v

>>> S = 'spam'
>>> for (offset, item) in enumerate(S):
... print(item, 'appears at offset', offset)
...
s appears at offset 0
p appears at offset 1
a appears at offset 2
m appears at offset 3

>>> E = enumerate(S)
>>> E
<enumerate object at 0x0000000002A8B900>
>>> next(E)
(0, 's')
>>> next(E)
(1, 'p')
>>> next(E)
(2, 'a')
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群