> 文档中心 > 牛客刷题总结——Python入门06:元组、字典

牛客刷题总结——Python入门06:元组、字典

在这里插入图片描述

🤵‍♂️ 个人主页: @北极的三哈 个人主页

👨‍💻 作者简介:Python领域优质创作者。

📒 系列专栏:《牛客题库-Python篇》

🌐推荐《牛客网》——找工作神器|笔试题库|面试经验|实习经验内推求职就业一站解决

👉 点击链接进行注册学习

牛客刷题总结——Python入门06:元组、字典

文章目录

    • 08 元组 NP62-66
      • 1.什么是元组
      • 2.元组的创建方式
      • 3.元组的遍历
      • NP62 运动会双人项目
      • NP63 修改报名名单
      • NP64 输出前三同学的成绩
      • NP65 名单中出现过的人
      • NP66 增加元组的长度
    • 09 字典 NP67-75
      • 1.字典操作函数
      • 2.字典操作方法
      • NP67 遍历字典
      • NP68 毕业生就业调查
      • NP69 姓名与学号
      • NP70 首都
      • NP71 喜欢的颜色
      • NP72 生成字典
      • NP73 查字典
      • NP74 字典新增
      • NP75 使用字典计数
      • **`推 荐:牛客题霸-经典高频面试题库`**

08 元组 NP62-66

元组学习链接:http://t.csdn.cn/RqgMt
牛客刷题总结——Python入门06:元组、字典

1.什么是元组

元组:Python内置的数据结构之一,是一个不可变序列。

不可变序列与可变序列

  • 不变可变序:字符串元组
    不变可变序列:没有增、删,改的操作
# 修改后对象地址会发生改变s = 'hello'print(id(s))  # 2533879685808s = s + 'world'print(id(s))  # 2533879671984print(s)  # helloworld
  • 可变序列:列表字典
    可变序列:可以对序列执行增、删、改操作,对象地址不发生更改
# 可变序列:可以执行增删改操作,对象地址不发生改变lst = [10, 20, 40]print(id(lst))lst.append(50)print(id(lst))

牛客刷题总结——Python入门06:元组、字典

2.元组的创建方式

  1. 直接小括号()
# 1.使用()t = ('python', 'java')print(t)  # ('python', 'java')print(type(t))  # 
  1. 使用内置函数tuple()
# 2.使用内置函数tuple()t2 = tuple(('java', 'python'))print(t2)  # ('java', 'python')print(type(t2))  # 
  1. 只包含一个元组的元素需要使用逗号,和小括号()
# 3.只包含一个元素,需要使用逗号和小括号(只有一个元素的时候必须加上,)t3 = ('hello', )print(t3)  # ('hello',)print(type(t3))  # 
  1. 空元组创建方式
# 空元组创建方式t4 = ()t5 = tuple()print('空元组', t4, t5)  # 空元组 () ()print('空列表', [], list())  # 空列表 [] []print('空字典', {}, dict())  # 空字典 {} {}# print('空集合', {}, set())

为什么要将元组设计成不可变序列

在多任务环境下,同时操作对象时不需要加锁,因此,在程序中尽量使用不可变序列 。
注意事项:元组中存储的是对象的引用

  • 如果元组中对象本身不可对象,则不能再引用其它对象。
  • 如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变。

这样设计的原因是,元组的不可变性保证了数据的完整性,这样如果有多个地方都用到了元组,我们可以保证它的数据不会被改变。并且,相较于列表,元组的读取速度更快,占用的内存空间更小,并且可以作为字典的key去使用。

# 这样设计的原因是,元组的不可变性保证了数据的完整性,这样如果有多个地方都用到了元组,我们可以保证它的数据不会被改变。# 并且,相较于列表,元组的读取速度更快,占用的内存空间更小,并且可以作为字典的key去使用。t = (10, [20, 30], 40)print(t)  # (10, [20, 30], 40)print(type(t), id(t))  #  2972759079744print(t[0], type(t[0]), id(t[0]))  # 10  140726042761152print(t[1], type(t[1]), id(t[1]))  # [20, 30]  2972768483776print(t[2], type(t[2]), id(t[2]))  # 40  140726042762112t[1].append(100)print(t, id(t))  # (10, [20, 30, 100], 40) 2972759079744

3.元组的遍历

元组是可迭代对象,所以可以使用for...in进行遍历

# 元组遍历t = ('hello', 'java', 90)print(t[0])print(t[1])print(t[2])for item in t:    print(item, end=' ')

牛客刷题总结——Python入门06:元组、字典
列表类型覆盖了元组类型的所有主要功能。

NP62 运动会双人项目

在线编程跳转链接

t = (input(), input())print(t)

NP63 修改报名名单

在线编程跳转链接

entry_form = ('Niuniu', 'Niumei')print(entry_form)try:    entry_form[1] = 'Niukele'except:    print('The entry form cannot be modified!')

NP64 输出前三同学的成绩

在线编程跳转链接

s = input().split(' ')t = tuple(s)print((t[0:3]))

NP65 名单中出现过的人

在线编程跳转链接

t = tuple(['Tom', 'Tony', 'Allen', 'Cydin', 'Lucy', 'Anna'])print(t)name = input()if name in t:    print('Congratulations!')else:    print('What a pity!')

NP66 增加元组的长度

在线编程跳转链接

t = tuple(range(1, 6))print(t)print(len(t))t1 = t + tuple(range(6, 11))print(t1)print(len(t1))

09 字典 NP67-75

字典学习链接:http://t.csdn.cn/R6agr
牛客刷题总结——Python入门06:元组、字典

1.字典操作函数

操作函数 描述
dict() 生成一个字典
len(d) 字典d元素的个数(长度)
min(d) 字典d中键的最最小值
max(d) 字典d中键的最最大值

2.字典操作方法

操作方法 描述
d.keys() 返回字典d所有键的信息
d.values() 返回字典d所有值的信息
d.items() 返回字典d所有键值对
d.get(key, default) 键存在则返回相应值,否则返回默认值default
d.pop(key, default) 键存在则返回相应值,同时删除键值对,否则返回默认值default
d.popitem() 随机从字典中取出一个兼职对,以元组(key, value)的形式返回,同时将该键值对从字典中删除。
d.clear() 删除所有的键值对,清空字典

NP67 遍历字典

在线编程跳转链接

# 创建一个字典 operators_dictoperators_dict = {'<': 'less than','==': 'equal'} # 先打印一行print('Here is the original dict:')# 在使用 for 循环 遍历 使用 sorted 函数 排序 包含 operators_dict 所有键值对的列表for key, value in sorted(operators_dict.items()):    # 输出类似字符串    print(f'Operator {key} means {value}.') # 增加键值对operators_dict['>'] = 'greater than'# 输出一个换行print()# 在打印一行字符串print('The dict was changed to:')# 再来个和上述一样的for循环for key, value in sorted(operators_dict.items()):    print(f'Operator {key} means {value}.')

NP68 毕业生就业调查

在线编程跳转链接

survey_list = ['Niumei', 'Niu Ke Le', 'GURR', 'LOLO']result_dict = {'Niumei': 'Nowcoder', 'GURR': 'HUAWEI'} for i in survey_list:    if i in result_dict.keys(): print(f'Hi, {i}! Thank you for participating in our graduation survey!')    else: print(f'Hi, {i}! Could you take part in our graduation survey?')

NP69 姓名与学号

在线编程跳转链接

my_dict_1 = {'name': 'Niuniu', 'Student ID': 1}my_dict_2 = {'name': 'Niumei', 'Student ID': 2}my_dict_3 = {'name': 'Niu Ke Le', 'Student ID': 3}dict_list = []dict_list.append(my_dict_1)dict_list.append(my_dict_2)dict_list.append(my_dict_3) for i in dict_list:    key, value = i['name'], i['Student ID']    print(f"{key}'s student id is {value}.")

NP70 首都

在线编程跳转链接

cities_dict = {'Beijing': {'capital': 'China'},'Moscow': {'capital': 'Russia'},'Paris': {'capital': 'France'}} for city in sorted(cities_dict.keys()):    city_value = cities_dict[city]    for item in city_value: print(f'{city} is the {item} of {city_value[item]}!')

NP71 喜欢的颜色

在线编程跳转链接

result_dict = {    'Allen': ['red', 'blue', 'yellow'],    'Tom': ['green', 'white', 'blue'],    'Andy': ['black', 'pink']}for i in sorted(k for k in result_dict):##列表生成式生成key的列表    print("%s's favorite colors are:" % i)    for x in result_dict[i]: print(x)

NP72 生成字典

在线编程跳转链接

a =input()b = input()names = a.split()language = b.split()dict_a = dict(zip(names,language))print(dict_a)

NP73 查字典

在线编程跳转链接

dict1 = {'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}a = input()for i in dict1[a]:    print(i,end=' ')

NP74 字典新增

在线编程跳转链接

letter = input()word = input()d = {    "a": ["apple", "abandon", "ant"],    "b": ["banana", "bee", "become"],    "c": ["cat", "come"],    "d": "down",    letter: word,}d[letter] = wordprint(d)

NP75 使用字典计数

在线编程跳转链接

list1=list(input())dict1={}for i in list1:    if i in dict1: dict1[i]+=1    else: dict1[i]=1print(dict1)

推 荐:牛客题霸-经典高频面试题库

🌐 找工作神器-|笔试题库|面试经验|大厂面试题 👉 点击链接进行注册学习
牛客刷题总结——Python入门06:元组、字典