练习一,逐一显示指定列表中的所有元素;
//方法一 In [25]: l1 Out[25]: [1, 2, 3, 4] In [26]: while l1: ....: print l1[0] ....: l1.pop(0) ....: 1 2 3 4 //方法二 In [66]: count = 0 In [67]: count Out[67]: 0 In [68]: while count < len(l1): ....: print l1[count] ....: count += 1 ....: 1 2 3 4
练习二,求100以内所有偶数之和;
In [215]: sum = 0; i = 0 In [216]: while i <= 100: .....: i+=1 .....: if i % 2 == 0: .....: sum = sum +i .....: In [217]: print sum 2550
练习三,逐一显示指定字典的所有值,并于显示结果结束后说明总键数;
In [91]: print d1 {‘y‘: 45, ‘x‘: 2, ‘z‘: 90} In [95]: while keylist: ....: print keylist[0] ....: keylist.pop(0) ....: else: ....: print len(d1) ....: y x z 3
练习四,创建一个包含了100以内所有奇数的列表;
In [96]: l1 = [] In [97]: x = 1 In [98]: while x < 100: ....: l1.append(x) ....: x += 2 ....: In [99]: print l1 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
练习五,逆序逐一显示一个列表的所有元素;
In [34]: l1 = [1,2,3,4] In [35]: while l1: ....: print l1[-1] ....: l1.pop() ....: 4 3 2 1
练习六,列表l1=[0,1,2,3,4,5,6],列表l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] ,以第一个列表中的元素为键,以第二个列表中的元素为值生成字典d1;
In [120]: d1={} In [121]: x=0 In [122]: l1=[0,1,2,3,4,5,6] In [123]: l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] In [130]: while x < len(l1): d1[l1[x]] = l2[x] x += 1 .....: In [131]: print d1 {0: ‘Sun‘, 1: ‘Mon‘, 2: ‘Tue‘, 3: ‘Wed‘, 4: ‘Thu‘, 5: ‘Fri‘, 6: ‘Sat‘}
本文出自 “Jessen Liu的博文” 博客,请务必保留此出处http://zkhylt.blog.51cto.com/3638719/1708089
原文地址:http://zkhylt.blog.51cto.com/3638719/1708089