Python-Day006

一、元组

Python的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法

names = ("eos666","jack","eric")

它只有2个方法,一个是count,一个是index,完毕。 

 

a、创建空元组

 元组中只包含一个元素时,需要在元素后面添加逗号;元组与字符串类似,下标索引从0开始,可以进行截取,组合等。

b、元组的查跟列表相似,参考(3、列表(list));其中元组中的元素是不可变的,因此没有增删改元素。删除整个元组用 del tup1

c、元组函数有

(1)len(tuple)计算元组元素个数。(看3、列表

(2)max(tuple)返回元组中元素最大值。(看3、列表

(3)min(tuple)返回元组中元素最小值。(看3、列表

(4)tuple(seq)将列表转换为元组。

实例1:针对字典 会返回字典的key组成的tuple,元组返回自身

实例2:

aList = [123, 'xyz', 'zara', 'abc']
aTuple = tuple(aList)
print ("Tuple elements : ", aTuple)

 

#结果
Tuple elements :  (123, 'xyz', 'zara', 'abc')

 

二、字典(dictionary)

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号{}中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键必须是唯一的,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组

a、字典查询

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age'])
print("dict['Class']: ", dict['Class'])

 

 

 

b、增加及修改字典元素

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8  # update existing entry
dict['School'] = "DPS School"  # Add new entry
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])
#结果
dict['Age']:  8
dict['School']:  DPS School

c、删(del)

复制代码
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict1['Name']  # 删除键是'Name'的条目
print(dict1)
dict1.clear()  # 清空词典所有条目
print(dict1)
del dict1  # 删除词典
print(dict1)
复制代码
{'Age': 7, 'Class': 'First'}
{}
  File "D:/Users/Administrator/PycharmProjects/s14/day2/test/dictionary.py", line 26, in <module>
    print(dict1)
NameError: name 'dict1' is not defined

d、字典特性

(1)不允许同一个键出现两次(无序性)

(2)键必须不可变,所以可以用数字,字符串或元组充当,但是用列表就不行。

dict = {['Name']: 'Zara', 'Age': 7}
输出结果
Traceback (most recent call last):
  File "D:/Users/Administrator/PycharmProjects/s14/day2/test/dictionary.py", line 27, in <module>
    dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'

e、字典内置函数及方法

(1)len(dict)  计算字典元素个数,即键的总数

(2)str(dict)  及type(dict)

复制代码
dict1 = {'Name': 'Zara', 'Age': 7}
print(dict1)
print(type(dict1))
print(type(str(dict1)))
#结果
{'Name': 'Zara', 'Age': 7}
<class 'dict'>
<class 'str'>
复制代码

 (3)clear(dict) 删除字典中的所有元素

复制代码
dict = {'Name': 'Zara', 'Age': 7}
print ("Start Len : %d" %  len(dict))
dict.clear()
print ("End Len : %d" %  len(dict))
#结果
Start Len : 2
End Len : 0
复制代码

(4)dict.fromkeys(seq[,value])  用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。

复制代码
seq = ('name', 'age', 'sex') #或者seq = ['name', 'age', 'sex']
dict = dict.fromkeys(seq)
print ("New Dictionary : %s" %  str(dict))
dict = dict.fromkeys(seq,'10')
print ("New Dictionary : %s" %  str(dict))
#结果
New Dictionary : {'sex': None, 'age': None, 'name': None}
New Dictionary : {'sex': '10', 'age': '10', 'name': '10'}
复制代码

(5)dict.get(key, default=None)  返回指定键的值,如果值不在字典中返回默认值。

dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" %  dict.get('Age'))
print ("Value : %s" %  dict.get('Sex'))
#结果
Value : 27
Value : None

(6)dict.items()  以列表返回可遍历的(键, 值) 元组数组。

 View Code

(7)dict.keys()   函数以列表返回一个字典所有的键。

dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" %  dict.keys())
#结果
Value : dict_keys(['Name', 'Age'])

 (8)dict.setdefault(key, default=None)  和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。

复制代码
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" %  dict.setdefault('Age', None))
print ("Value : %s" %  dict.setdefault('Sex', None))
print(dict)
#结果
Value : 7
Value : None
{'Age': 7, 'Sex': None, 'Name': 'Zara'}
复制代码

(9)dict.update(dict2)  把字典dict2的键/值对更新到dict里;存在即替换,不存在即添加。

dict = {'Name': 'Zara', 'Age': 7}
dict2 = {"Name":"John",'Sex': 'female' }
dict.update(dict2)
print("Value : %s" %  dict)
#结果
Value : {'Sex': 'female', 'Age': 7, 'Name': 'John'}

 

三、字符串操作   

特性:不可修改 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/17 11:09
# @Author  : EOS666
# @Site    : 
# @File    : lesson_dict.py
# @Software: PyCharm


st = 'hello kitty {name} is {age}'

#摘一些重要的字符串方法
print(st.count('l'))  # 统计l出现的次数
print(st.center(50,'#')) # 字符串居中显示,两边用#被齐
print(st.startswith('he')) # 判断字符串是否以 he 开头
print(st.find('t'))  # 查找字符串中出现的 t ,返回匹配到第一个的下标
print(st.format(name='alex',age=32)) # 字符转换,变量替代
print('My tItle'.lower())  # 全部转换成小写
print('My title'.upper())  # 全部转换成大写
print('\tMy tLtle\n'.strip()) # 去掉字符串开头与结尾的特殊字符或者空格
print('My title title'.replace('title', 'lesson')) #替换
print('My title title'.split('i',1))   # 以 i 进行切割,默认从左到右,只切割1次

  

结果:

 

第五天课程的复习总结

1、列表可以增删改查,元组是不可修改的列表,字符串是不可以修改的。

2、列表,元组是有序的,字典是无序的,字典的key唯一

3、列表字典可以嵌套列表,可以嵌套字典,可以嵌套多层

4、字典不需要保存下标,是通过key来找值(value)

 

posted on 2018-04-17 21:26  EOS666  阅读(102)  评论(0)    收藏  举报

导航