File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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 ))
You can’t perform that action at this time.
0 commit comments