Python基础入门(四)

Python基础入门(四)

一、本课目标
  • 理解并掌握 “元组” 的概念及使用
  • 理解并掌握 “字典” 的概念及使用
  • 理解并掌握 “集合” 的概念及使用
二、元组
  • 元组与列表类似,不同之处在于元组的元素不能修改

  • 元组使用小括号(),列表使用方括号[ ]

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

  • 元组中只包含一个元素时,需要在元素后面添加逗号

  • 元组与字符串类似,下标索引从0开始,可以进行截取,组合等

    l = ['a', 'b', 'c']
    t = ('a', 'b', 'c')
    l += 'd'
    l += ['b']
    t += ('b', )
    del l[0]
    print(l, t)
    t1 = (1, 2, 3)
    t2 = (4, 5, 6)
    t3 = t1 + t2
    print(t3)
    
    t1 = (1, 2, 3)
    
    t1 += (4, 5, 6)
    t2 = t1
    print(t1)
    print(t2)
    a = '12'
    print(id(a[0]), id(a[1]), id(a))
    a = a.replace('1', '2')
    print(id(a[0]), id(a[1]), id(a))
    b = [1, 2]
    print(id(b[0]), id(b[1]), id(b))
    b[0] = 2
    print(id(b[0]), id(b[1]), id(b))
    
    for i in ('a', 'b', 'c'):
        print(i)
    
    t = ('12', '012', '21')
    print(max(t), min(t))
    t = (16, 78, 89)
    print(max(t), min(t))
    
    l = [1,2,3]
    t = tuple(l)
    print(t)
    
  • 练习一:

    tupe1 = ('Google', 'Apache', '1997', 2000)
    tupe2 = (1, 2, 3, 4, 5, 6)
    print("tup1[0]:", tupe1[0])
    print("tup2[1:5]:", tupe2[1:5])
    
    tup1 = (12, 34.56)
    tup2 = ('abc', 'xyz')
    tup3 = tup1 + tup2
    print(tup3)
    
    print(len((1, 2, 3)))
    a = (1, 2, 3)
    b = (4, 5, 6)
    c = a + b
    print(c)
    a += b
    print(a)
    print(('Hi!,' * 4))
    print(3 in (1, 2, 3))
    for x in (1, 2, 3):
        print(x, end='')
    
  • 练习二:

    tup = ('Google', 'Apache', 'Taobao', 'Wiki', 'Weibo', 'Weixin')
    print(tup[1])
    print(tup[-2])
    print(tup[1:])
    print(tup[1:4])
    
    tuple1 = ('Google', 'Apache', 'Taobao')
    print(len(tuple1))
    
    tuple2 = ('5', '4', '8')
    print(max(tuple2))
    print(min(tuple2))
    
    list1 = ['Google', 'Apache', 'Taobao', 'Baidu']
    tuple1 = tuple(list1)
    print(tuple1)
    
三、字典的概念
  • 字典是另一种可变容器模型,且可存储任意类型对象
  • 字典的每个键值key = >value对用冒号:分隔,每个对之间用逗号(,)分隔,整个字典包括在花括号{}中,格式如下所示:
    • d = {key1: value1, key2 : value2, key3 : value3}
    • 键必须是唯一的,但值则不必

在这里插入图片描述

四、字典操作
  • 创建空字典

    • 使用大括号{ }
    • 使用函数dict()
  • 访问字典里的值

    • 通过[键]
    • 通过 for in
  • 修改字典

    • 通过字典[值] = 值 添加或更新
    • 通过del字典[键]删除
#字典
d = {
   
   }
print(tuple(d))
d = {
   
   'a':1, 'b':2, 'c':3}
print(d)
d = {
   
   'a':1, 'b':2, 'c':3, 'a':7, 5:6}
print(d)
d = dict(a=1, b=2, c=3)
print(d)

d = {
   
   'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
print(d['c'])
print(d['f']) # error

for i in d.items():
    print(i)
for k,v in d.items():
    print(k, v)
for k in d:
    print(k)
for k in d.keys():
    print(k)
for v in d.values():
    print(v)
for k in d:
    print(k, d[k])

d= {
   
   'apple':
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI拾荒者_阿蛮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值