Python基础语法学习6

元组

1.元组就是不可变的列表

列表获取元素的方法都适用于元组

# 获取单个元素
tuple2 = ("1111", "2222", "3333", "4444", "5555")
print(tuple2[1])  # 2222
print(tuple2[-1])  # 5555

# 遍历
for x in tuple2:
    print("x:", x)
for index, item in enumerate(tuple2):
    print(index, item)

# 切片
print(tuple2[::-1])  # ('5555', '4444', '3333', '2222', '1111')

# 列表相关操作都适用于元组
print((1, 2, 3) + ("a", "c", "b"))  # (1, 2, 3, 'a', 'c', 'b')
print((1, 2, 3) * 3)  # (1, 2, 3, 1, 2, 3, 1, 2, 3)
print((1, 2, 3) == (1, 2, 3))  # True
print((1, 2, 3) == (1, 3, 2))  # False
print((1, 2, 3) > (1, 3, 3))  # False
print(1 in (1, 2, 3))  # True

num = (1, 5, 3, 6, 9, 8, 4, 5, 8, 4, 555)
print(max(num))  # 555
print(min(num))  # 1
print(sorted(num))  # [1, 3, 4, 4, 5, 5, 6, 8, 8, 9, 555]
print(len(num))  # 11
print(tuple(num))  # (1, 5, 3, 6, 9, 8, 4, 5, 8, 4, 555)
print(tuple("cccc"))  # ('c', 'c', 'c', 'c')

# 相关方法
num = (1, 5, 3, 6, 9, 8, 4, 5, 4, 4, 4)
print(num.count(4))  # 4
print(num.index(4))  # 6

2.元组特有的一些方法和功能

(1)只有一个元素的元组:()中唯一的元素后需要添加逗号

list1 = [100]
print(type(list1))  # <class 'list'>
tuple1 = (100)
print(type(tuple1))  # <class 'int'>
tuple1 = (100,)
print(type(tuple1))  # <class 'tuple'>

(2)直接多个数据用逗号隔开表示的也是一个元组(元组的括号在没有歧义的时候可以省略)

tuple1 = (10, 20, 30)
tuple2 = 10, 20, 30
print(type(tuple2), tuple2)  # <class 'tuple'> (10, 20, 30)
tuple4 = tuple2 + tuple1
print(tuple4)  # (10, 20, 30, 10, 20, 30)

(3)获取元素的时候可以通过让变量的个数和元组中元素的个数保持一致,来分别获取元组中每个元素的值

point = (10, 20)
x, y = point
print(x, y)  # 10 20

(4)让变量个数少于元组中元素的个数,并且在一个变量前加*

先让没有*号的变量依次获取元素,然后把剩下的所有的元素作为一个列表返回

stu = ("cc", 22, "男", 77, 78, 76, 74)
name, age, gender, *scores = stu
print(name, age, gender)  # cc 22 男
print(scores)  # [77, 78, 76, 74]

a, *b, c = stu
print(a, c)  # cc 74
print(b)  # [22, '男', 77, 78, 76]

字典

1.什么是字典(dict)

字典是容器型数据类型的数据,将{}作为容器的标志,里面多个元素用逗号隔开(其中元素必须是键值对)
{键1:值1,键2:值2,键3:值3,…}
字典是可变的(支持增删改);字典是无序的(不支持下标操作)
字典的元素:键是不可变的,唯一的;值可以是任何类型的数据,并且可以重复

dict1 = {
    "n": "a",
    "n": "b11"
}
print(dict1)  # {'n': 'b11'}

dict2 = {
    "name": "cc",
    "variety": "4444",
    "color": "黄色",
    "age": 1
}
print(dict2["name"])

2.元素的增删改查

(1)查 – 获取字典的值

1.获取单个值
1.字典[key] – 获取字典中指定key对应的值(如果key不存在会报错)
2.字典.get(key) – 获取字典中指定key对应的值(如果key不存在不会报错,返回None)
字典.get(key,默认值) – 获取字典中指定key对应的值(如果key不存在不会报错,返回的是默认值)

movie = {
    "name": "战狼",
    "director": "吴京",
    "actor": "吴京",
    "release_time": "2015",
    "kind": "动作/战争/军事"
}
movie1 = {
    "name": "沉默的羔羊",
    "director": "乔纳森·戴米",
    "actor": "茱迪·福斯特,安东尼·霍普金斯",
    "release_time": "1991",
    "kind": "惊悚"
}
print(movie["name"])  # 战狼
print(movie1["name"])  # 沉默的羔羊
# print(movie["score"])  # KeyError: 'score'
print(movie1.get("kind"))  # 惊悚
print(movie1.get("score"))  # None
print(movie1.get("release_time", "2020-1-1"))  # 1991
print(movie1.get("score", 1))  # 1
print(movie["actor"])  # 吴京
print(movie1.get("actor"))  # 茱迪·福斯特,安东尼·霍普金斯

2.遍历字典

"""
方法一:
for 变量 in 字典:
    循环体(变量在循环体中得到的是字典的key)    
"""
for x in movie:
    print(x, movie[x])
"""
方法二:
for 变量1,变量2 in 字典.items():
    循环体(循环体中变量1取到的是所有的键,变量2取到的是所有键对应的值)
"""
for x, y in movie1.items():
    print(x, y)

(2)增/改 – 添加键值对/修改键值对的值

字典[key] = 值 – 当key不存在就是添加键值对;当key存在的时候就是修改key对应的值

subject = {
    "name": "Python",
    "score": 3,
    "class_hour": 44,
    "direction": ["数据分析", "web后端", "爬虫", "自动化测试", "自动化运维"]
}
print(subject)
subject["teacher"] = "Yt"
print(subject)
subject["score"] = 4
print(subject)

(3)删

del 字典[key] – 删除字典指定key对应的键值对
字典.pop(key) – 取出字典中指定key对应的值

del subject["class_hour"]
print(subject)

del_item = subject.pop("direction")
print(subject)
print(del_item)

字典的应用

# 练习:
# 1.定义一个变量同时保存条狗的信息,每条狗有:名字、年龄、性别、品种、价格和颜色
# 2.统计5条狗中公的有多少条
# 3.打印所有价格超过2000元的狗的名字
dog = [{"name": "1111", "age": 1, "sex": "1", "variety": "a", "price": 1000, "color": "y"},
       {"name": "2222", "age": 2, "sex": "1", "variety": "b", "price": 4444, "color": "y++"},
       {"name": "3333", "age": 3, "sex": "0", "variety": "c", "price": 2100, "color": "y+"},
       {"name": "4444", "age": 4, "sex": "0", "variety": "d", "price": 1777, "color": "y-"},
       {"name": "5555", "age": 5, "sex": "1", "variety": "e", "price": 1444, "color": "y--"}
       ]
count = 0
for i in dog:
    if i["sex"] == "1":
        count = count + 1
    if i["price"] > 2000:
        print(i["name"])
print(count)

字典的相关操作和方法

1.相关操作

(1)字典不支持加法,乘法和比较大小的运算
(2)判断是否相等

print({"a": 10, "b": 20} == {"b": 20, "a": 10})  # True

# is  --  判断两个数据的地址是否相等
a = {"a": 10}
b = {"a": 10}
c = a
print(id(a), id(b), id(c))  # 16342832 16342784 16342832
print(a == b)  # True
print(a is b)  # False
print(a is c)  # True

(3)in 和 not in
key in 字典 - 判断字典中是否有指定的key

dict1 = {"a": 10, "b": 20, "c": 30}
print(10 in dict1)  # False
print("b" in dict1)  # True

(4)相关函数:len\dict
len(字典) – 获取字典中键值对的个数

print(len(dict1))  # 3

dict(数据) – 将其他数据转换成字典(数据的要求:1.序列 2.序列中的元素还是序列 3.内部的序列有且只有两个元素,第一个元素不可变)

list1 = ["cc", (10, 20), ["name", "name1"]]
print(dict(list1))  # {'c': 'c', 10: 20, 'name': 'name1'}

2.将字典转换成其他数据

(1)将字典转换成列表/元组 – 将字典的key作为列表/元组的元素

stu = {"name": "1111", "age": 18, "score": 100}
print(list(stu))  # ['name', 'age', 'score']
print(tuple(stu))  # ('name', 'age', 'score')

(2)将字典转换成字符串

print(str(stu))  # {'name': '1111', 'age': 18, 'score': 100}

(3)将字典转换成布尔

print(bool({}))  # False
print(bool(stu))  # True

3.相关方法

(1)字典.clear()

stu = {"name": "1111", "age": 18, "score": 100}
stu.clear()
print(stu)  # {}

(2)字典.copy()

stu = {"name": "1111", "age": 18, "score": 100}
stu1 = stu.copy()
print(stu1)  # {'name': '1111', 'age': 18, 'score': 100}
stu["name"] = "2222"
print(stu1)  # {'name': '1111', 'age': 18, 'score': 100}
print(stu)  # {'name': '2222', 'age': 18, 'score': 100}

(3)dict.fromkeys(序列,默认值=None) – 创建一个新的字典,序列中所有的元素会作为新字典的key,默认值是所有key对应的值

new_dict = dict.fromkeys("abc")
print(new_dict)  # {'a': None, 'b': None, 'c': None}
new_dict = dict.fromkeys(["name", "age", "sex"], 0)
print(new_dict)  # {'name': 0, 'age': 0, 'sex': 0}

(4)字典.items(),字典.keys(),字典.values()

stu = {"name": "1111", "age": 18, "score": 100}
print(stu.items())  # dict_items([('name', '1111'), ('age', 18), ('score', 100)])
print(stu.keys())  # dict_keys(['name', 'age', 'score'])
print(stu.values())  # dict_values(['1111', 18, 100])

(5)字典.setdefault(key,value) – 在字典中添加键值对(单纯的添加键值对,不会修改)

stu = {"name": "1111", "age": 18, "score": 100}
stu.setdefault("weight", 50)
print(stu)  # {'name': '1111', 'age': 18, 'score': 100, 'weight': 50}

(6)字典1.update(字典2) – 将字典2中所有的键值对全部添加到字典1中

stu = {"name": "1111", "age": 18, "score": 100}
stu.update({"a": 10, "b": 20})
print(stu)  # {'name': '1111', 'age': 18, 'score': 100, 'a': 10, 'b': 20}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值