Python基础知识(二)

一、字典

  • 字典是一种将键(key)映射到值(value)的无序数据结构 。
  • 字典的值可以是任何值,如列表,函数,字符串等;键(key)必须是不可变的,例如,数字,字符串或元组等。
  • 对字典的操作,即对字典的键进行操作。
# 定义一个字典
dict = {'start':'There is a new start','second':'This a dictionary','third':'Let\'s go'}
print(dict)	# {'start': 'There is a new start', 'second': 'This a dictionary', 'third': "Let's go"}

# 访问字典中的值
print(dict['second'])	# This a dictionary

# 向字典中一次加入键值对
dict['four'] = 'This is add for dictionary'
print(dict)		
''' 
{'start': 'There is a new start', 
'second': 'This a dictionary', 
'third': "Let's go", 
'four': 'This is add for dictionary'}
'''

# 错误示例,不是所有的值可以作Key
dict[['four']] = 'This is add for dictionary'	# 会报错 TypeError: unhashable type: 'four'

# 向字典中批量加入键值对
dict.update({'five':'This a fifth dictionary key-value','six':'This a sixth dictionary key-value'})
print(dict)
'''
{'start': 'There is a new start', 
'second': 'This a dictionary', 
'third': "Let's go", 
'five': 'This a fifth dictionary key-value', 
'six': 'This a sixth dictionary key-value'}
'''

# 删除字典中的某一个键值对,不获取删除的键对应的值
del dict['third']
print(dict)	# {'start': 'There is a new start', 'second': 'This a dictionary'}
# 删除字典中的某一个键值对,获取删除的键对应的值
print(dict.pop('third'))	# Let's go
# 使用get()方法返回给定键的值
# 如果要获取的键存在,则返回字典中对应的值;否则返回给定的默认值
dict = {'start':'There is a new start','second':'This a dictionary','third':'Let\'s go'}
print(dict.get('start',0))	# There is a new start

# 如果要获取不存在的键,其值未设置默认值,则默认返回None
print(dict.get('ten'))	# None

# 如果要获取不存在的键,其值设已经设置默认值,则返回默认值
print(dict.get('ten',0))	# 0
# 遍历返回字典中的所有键
dict = {'start':'There is a new start','second':'This a dictionary','third':'Let\'s go'}
print(dict.keys())	# dict_keys(['start', 'second', 'third'])

# 遍历返回字典中的所有值
print(dict.values()) # dict_values(['There is a new start', 'This a dictionary', "Let's go"])

# 通过key遍历输出key
for key in dict:
    print(key)
''' 
start
second
third 
'''    

# 通过键值对,遍历输出键值对
for key,value in dict.items():
    print(key,value)
'''
start There is a new start
second This a dictionary
third Let's go
'''    
   

二、元组

  • 元组是一种序列,与列表类似。
  • 元组和列表之间的区别:
    • 列表可变,元组不可变。
    • 列表使用方括号,元组使用括号。
  • 01、初始化元组
# 初始化空元组
# 方法一
emptyTuple = ()

# 方法二,使用元组函数tuple()初始化空元组
emptyTuple = tuple()
# 初始化非空元组
# 方法一,使用逗号分隔值的序列来初始化元组
tup = (3,5,4,9)

# 方法二,不使用逗号分隔值的序列来初始化元组
tup = 3,5,4,9
# 初始化仅包含一个值的元组,需要在序列值后面添加一个逗号
# 方法一
tup = ('Hello',)
tup = ('Hello')	# 该变量为一个字符串,而非元组

# 方法二
tup = 'Hello',

  • 02、访问元组内的值
# 正索引访问元组
tup = (3,5,4,9)
print(tup[1])	# 5

# 负索引访问元组
print(tup[-1])	# 9
  • 03、基于已存在的元组,合并创建新的元组
    • 元组是不可变的,我们只能通过合并已有元组来创建新的元组
# 错误示例
tup = (3,5,4,9)
tup[2] = 6	# 报错:TypeError: 'tuple' object does not support item assignment
# 初始化一个元组
tup1 = ('first','second')
# 初始化第二个元组
tup2 = ('third',)
# 合并创建新的元组
new_tup = tup1 + tup2
print(new_tup)	# ('first', 'second', 'third')
  • 04、元组常用方法
tup = ('first','second','first',2,5)
# index(),返回对应值的第一个索引
print(tup.index('second'))	# 1

# count(),统计返回值在元组中出现的次数
print(tup.count('first'))	# 2
  • 05、遍历元组
tup = ('first','second','first',2,5)
for item in tup:
    print(item)
'''
first
second
first
2
5
'''    
  • 06、元组拆包
x,y = (2,3)
print("Value of x is {}, the value of y is {}.".format(x,y))	
# Value of x is 2, the value of y is 3.
  • 07、枚举
    • 枚举函数返回一个元组,其中包含每次迭代的计数(从默认为0的开始)和迭代序列获得的值
tups = ('first','second','first',2,5)
print(enumerate(tups))	# <enumerate object at 0x000002737049B680>
# 遍历输出
for index,tup in enumerate(tups):
    print(index,tup)
'''
0 first
1 second
2 first
3 2
4 5
'''    

三、元组相对列表的优势

  • 01、访问元组比列表快
    • 如果要定义一组常量,要做的工作是迭代它。元组比列表更适合定义常量
    • 使用timeit库部分测量性能差异 ,为Python代码计时(以秒为单位)
import timeit
print('Tuple time:',timeit.timeit('x = (1,2,3,4,5,6)', number = 1000000))
print('List time:',timeit.timeit('x = [1,2,3,4,5,6]', number = 1000000))
'''
Tuple time: 0.049612699999999996
List time: 0.10503829999999999
'''
  • 02、元组可以用作字典键,列表不可以用作字典键
    • 字典键是不可变的,而一些元组可以用作字典键,比如,字符串、数字等等
    • 列表不可以用作字典键,因为列表是可变的
# 元组作字典键
tup = {('this','is'):1,('is','a'):2,('a','sentence'):3}
print(tup)	# {('this', 'is'): 1, ('is', 'a'): 2, ('a', 'sentence'): 3}
# 列表用作字典键,会报错
tup = {['this','is']:1,['is','a']:2,['a','sentence']:3}
print(tup)	# TypeError: unhashable type: 'list'
  • 03、元组可以作集合的值,列表不可以作集合的值
# 元组作集合的值
tup = {('this','is'),('is','a'),('a','sentence')}
print(tup)	# {('this', 'is'), ('a', 'sentence'), ('is', 'a')}
# 列表用作集合的值,会报错
tup = {['this','is'],['is','a'],['a','sentence']}
print(tup)	# TypeError: unhashable type: 'list'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值