您的位置:首页 > 编程语言 > Python开发

Python学习记录——Python tuple、list、dict

2017-07-31 23:59 477 查看
来吧!我们继续学习python编程语言。

记载内容目录:

1 元组

2 列表

3 字典

1.元组

定义和引用:

定义方法:有两种
tup1 = ('Google', 'Runoob', 1997, 2000)  # 推荐方法,使用小括号把元素括起来
tup2 = "a", "b", "c", "d"


使用方法:
print(type(tup1)) #输出结果:<type 'tuple'>  输出类型
print(tup1[0])  #输出结果:Google	获取元组元素
print(tup1[1:3]) #输出结果:('Runoob', 1997) 截取一段元素
print( tup1 + tup2 )  # ('Google', 'Runoob', 1997, 2000, 'a', 'b', 'c', 'd') 拼接元组
print( 1997 in tup1 ) # True 查询是否包含相关元素


常用方法:
print( len(tup1)  ) #输出结果: 4  计算元组元素个数
print( max(tup1) ) #输出结果: Runoob  求出最大的那个数
print( min(tup1) ) #输出结果: 1997	求出最小的那个数
print(type( tuple(tup1) )) #输出结果: <type 'tuple'> 转换成元组
print(type(list(tup1)))  # 输出结果:  <type 'list'> 转换成数组


注意点:

1.元素不能被修改

2.只有一个元素的时候需要加逗号,否则就变成数值。
print(type(("fsdf"))) # <type 'str'>
print(type(("fdsf",))) # <type 'tuple'>


3.推荐使用小括号把元素括起来的方法定义元组

2.列表

定义和引用:

定义方法:
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = ["a", "b", "c", "d"]


使用方法:
print(type(list1)) #<type 'list'> 类型
print(list1[0]) #Google 获取列表元素
print(list1[1:3]) #['Runoob', 1997]	接取一段元素
print(list1 + list2) #['Google', 'Runoob', 1997, 2000, 'a', 'b', 'c', 'd'] 拼接列表
print(1997 in list1) #True	查询是否包含相关元素


常用方法:

list1.append("sdfsdfs") #在列表末尾添加新的对象
print(list1)	#['Google', 'Runoob', 1997, 2000, 'sdfsdfs']

list1.insert(len(list1), "insert")#将对象插入列表
print(list1) #['Google', 'Runoob', 1997, 2000, 'sdfsdfs', 'insert']

print(list1.pop())#获取元素并移除该元素 默认是最后一个
print(list1) #['Google', 'Runoob', 1997, 2000, 'sdfsdfs']

list1.remove('Runoob')#移除列表中某个值的第一个匹配项
print(list1) # ['Google', 1997, 2000, 'sdfsdfs']

del list0[0]	# 删除第0个元素

print("list.count  " , list1.count("Runoob"))#统计元素出现的次数 ('list.count  ', 1)
print("list.index  ",list1.index(list1[1])) #找出相等元素的第一个索引 ('list.index  ', 1)

#list1.sort([func])#对原列表进行排序 func是排序的方法

list1 = []   #清空列表 直接赋值为空 clear方法用不了,就这种方式代替
#print("list.clear   " , list1)


3.字典 / 键值对 (java的hashTable,C++的map)

定义和引用:

定义:

dict = {'Alice': '2341', 'Beth': '9102'}


使用方法:
print(dict["Alice"]) #结果输出:2341 使用key获取值

dict["NewVal"] = "NewVal" #添加/修改新元素
print(dict)  #结果输出:{'NewVal': 'NewVal', 'Beth': '9102', 'Alice': '2341'}

del dict["NewVal"] #删除一元素
print(dict) #结果输出:{'Beth': '9102', 'Alice': '2341''}

print(type(dict)) #<type 'dict'>


常用方法:
# 遍历输出
for key,val in dict.items():
print key ,val

#获取所有的key
print type(dict.keys())

#查询字典里面是否包含该key
print("Alice" in dict)


迭代器与for循环
list1 = [23,44,22,11,33,55]
print list1  # [23,44,22,11,33,55]
for x in iter(list1):
if x == 11:


list1.remove(x) else: print(x) #23,44,22,55 #注意到结果了么? 在迭代过程中不能删除子元素




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 编程语言
相关文章推荐