Python基础数据结构之大循环(for list,set,dict,tuple)
本章是Python基础数据结构的第六篇,由于之前没有接触过太多的Python版本的数据结构,所以在学习的过程中集百家之长和自己的见解,加以实践,学习Python。Python中用到tuple的方法,和注意事项都以代码的形式体现#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time: 2017-5-3 10:41# @Autho
·
本章是Python基础数据结构的第六篇,由于之前没有接触过太多的Python版本的数据结构,所以在学习的过程中集百家之长和自己的见解,加以实践,学习Python。
Python中用到tuple的方法,和注意事项都以代码的形式体现
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017-5-3 10:41
# @Author : coderManFans
# @Site : Python基础数据之大循环
# 本篇是基础数据的for循环操作,同时学习如何使用复杂的基础数据
# 通过组合不同数据结构可以满足不同数据模型的构建需求
# @File : dataforearchDemo.py
# @Software: PyCharm
#1. for 循环 list
#1.1 循环单个元素的list
list1 = [1,2,3,'2','2',"323",33.22]
for i in list1:
print("i = "+str(i))
#1.2 循环多个元素的list 比如二维数组
list2 = [['u',1],['x',2],['w',3]]
for u,v in list2:
print("u = " + str(u) + ",v = " + str(v))
print("-----------------------------------------------------------")
#1.3 list里嵌套tuple的循环
list3 = [("a","sd",2323),("sd","sd23","sdf"),("sd",23,2323,2324)]
for i in list3:
print(str(i[0])+"----"+str(i[1]))
#1.4 list里嵌套dict的循环 每个dict的元素数量必须一样
list4 = [{"a":1,"b":2},{"a":1,"b":2},{"a":1,"b":2},{"a":1,"b":2},{"a":1,"b":2}]
#循环key
for k,v in list4:
print(k+"---"+v)
for di in list4:
for i in di.items():
print(i)
print("--------------------------------------")
#2. 循环set
set1 = set([2,3,34,332,23,2,3,3,3,3,4,3,4])
for s in set1:
print(s)
print("------------------------------")
#3. 循环tuple
tup1 = ('physics','chemistry','yyyy-dd-dd',999,0.0023)
for t in tup1:
print(t)
#3.1 tuple里内嵌list
tup2 = ([1,2],[2,3],[4,5],[5,6])
for t in tup2:
print(str(t[0])+"----"+str(t[1]))
#3.2 tuple里内嵌dict
tup3 = ({"a":"d"},{"a":'2'},{"a":"sd"},{"a":"1213"})
for t in tup3:
print(t['a'])
print(t.keys())
print(t.values())
print(t.items())
print("-------------------------------------------------------")
#4. dict遍历
dict1 = {"a":'a',"b":'b',"c":'c'}
for key,value in dict1.items():
print(str(key)+"---"+str(value))
更多推荐
已为社区贡献7条内容
所有评论(0)