python开发之for循环操作实例详解

时间:2021-05-22

本文实例讲述了python开发之for循环操作。分享给大家供大家参考,具体如下:

下面是我做的一些学习记录供大家参考:

#基本的for循环语句test_list = [2,"Jone",3,6,7,'hongten','hanyuan','good',"Tom"]#打印列表的长度print(len(test_list))#遍历列表for i in test_list: print(i)test_str = "hello,i'm hongten"print('打印字符串:' + test_str)#遍历一个字符串print('遍历一个字符串')for i in test_str: print(i)test_tuple = [("a",1),("b",2),("c",3),("d",4)]print(test_tuple)#遍历一个元组print('遍历一个元组')for (i,j) in test_tuple: print(i,j)test_dict = {'name':'hongten','age':'20','gender':'M','sports':'足球,乒乓球,游泳'}#字典迭代器for key in test_dict: print(key + ':' + test_dict[key])L1 = [1,3,5,7]L2 = [2,4,6,8]#使用zip将两个列表合并print(zip(L1,L2))for (i,j) in zip(L1,L2): print(i,j)print('#######################################################')L3 = L2[:]L3.remove(8)print('L1,L3列表为:')print(L1)print(L3)for (i,j) in zip(L1,L3): print(i,j)#可以看出来当长度不一的时候,多余的被忽略test_keys = ['name','age','gender','weight','hight']test_values = ['Hongten','20','M','55','170']#使用zip来构造一个字典print('字典中的keys:')print(test_keys)print('字典中的key对应的value:')print(test_values)print('构造字典后')test_dic = dict(zip(test_keys,test_values))for key in test_dic: print( key + ':' + test_dic[key])

运行效果:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>> 92Jone367hongtenhanyuangoodTom打印字符串:hello,i'm hongten遍历一个字符串hello,i'm hongten[('a', 1), ('b', 2), ('c', 3), ('d', 4)]遍历一个元组('a', 1)('b', 2)('c', 3)('d', 4)gender:Mage:20name:hongtensports:足球,乒乓球,游泳[(1, 2), (3, 4), (5, 6), (7, 8)](1, 2)(3, 4)(5, 6)(7, 8)#######################################################L1,L3列表为:[1, 3, 5, 7][2, 4, 6](1, 2)(3, 4)(5, 6)字典中的keys:['name', 'age', 'gender', 'weight', 'hight']字典中的key对应的value:['Hongten', '20', 'M', '55', '170']构造字典后gender:Mage:20name:Hongtenweight:55hight:170>>>

希望本文所述对大家Python程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章