Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 6ea5ada

Browse files
authoredFeb 21, 2018
练习高级特性的迭代
1 parent 4cf96a0 commit 6ea5ada

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
 

‎test4.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# 练习高级特性的迭代
2+
3+
4+
l = list(range(1,21))
5+
# 这个就是迭代
6+
for num in l:
7+
print(num)
8+
# 对元组的迭代
9+
t = (1,3,5,7,9)
10+
for num in t:
11+
print(num)
12+
# 还可以对字符串进行迭代
13+
s = 'jskldf'
14+
for c in s:
15+
print(c)
16+
17+
18+
# 判断一变量是否可迭代,用collections的Iterable
19+
from collections import Iterable
20+
print(isinstance(l,Iterable))
21+
print(isinstance(t,Iterable))
22+
print(isinstance(s,Iterable))
23+
# 可以看出结果都是True,证明可迭代
24+
25+
26+
# 还可以按下表来迭代
27+
for value,num in enumerate(t):
28+
print(value, num)
29+
30+
31+
# 作业:请使用迭代查找一个list中最小和最大值,并返回一个tuple:
32+
def getNum(L):
33+
if isinstance(L,list):
34+
max = min = L[0]
35+
for num in L:
36+
if num > max:
37+
max = num
38+
if num < min:
39+
min = num
40+
return (min, max)
41+
else:
42+
print('请输入一个列表')
43+
44+
45+
l = [9,5,456,8,54,4,45]
46+
print(getNum(l))

0 commit comments

Comments
 (0)
Please sign in to comment.