python-元组 字典 集合

元组 字典 集合

元组

---Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。

访问元组

a=('hello',100,3.14)
print(a[0])

修改元组

-----python中不允许修改元组的数据,包括不能删除其中的元素

count,index

a=('a','b','c','d','e','a')
print(a.index('a',0,4))	------0
print(a.count('b'))		------1

定义只有一个数据的元组

​ ------定义只有一个元素的元组,需要在唯一的元素后写一个逗号

a=(11)
print(a)
print(type(a))-----<class 'int'>

a=(11,)
print(a)
print(type(a))-----<class 'tuple'>

转换

---列表转换为元组,元组转换为列表

words=['hello','yes','good','hi']
nums=(9,4,3,1,8,5,6,5,9)

print(tuple(words))-----('hello', 'yes', 'good', 'hi')
print(list(nums))-----[9, 4, 3, 1, 8, 5, 6, 5, 9]

join使用

print('*'.join(heights))
print(''.join(('h','e','l','l','o')))

-------
189*174*170
hello

字典

字典基本使用

------字典格式:{键1:值1, 键2:值2, 键3:值3, ..., 键n:值n}

info ={'name':'班长','id':1000,'sex':'f'}
print(info['name'])----班长 #字典使用键来获取对应的值

字典的增删改查

查看

info ={'name':'班长','id':1000,'sex':'f'}
print(info['name'])
print(info.get('age'))	----None#获取不存在的key不会出现异常
print(info.get('age','18'))-----获取一个不存在的key,会提供一个默认值

修改元素

info ={'name':'班长','id':1000,'sex':'f'}
print('修改之前的字典为%s:'%info)
info['id']=200
print('修改之后的%s:'%info)
---修改之前的字典为{'name': '班长', 'id': 1000, 'sex': 'f'}:
---修改之后的{'name': '班长', 'id': 200, 'sex': 'f'}:

添加元素

info ={'name':'班长','sex':'f'}
info['id']=100
print(info) -----{'name': '班长', 'sex': 'f', 'id': 100}

删除

del

删除指定元素

info ={'name':'班长','sex':'f'}
del info['name']
print(info)-----{'sex': 'f'}

删除整个字典

info ={'name':'班长','sex':'f'}
del info
print(info)----结果显示为报错

clear

---清空整个字典

info ={'name':'班长','sex':'f'}
info.clear()
print(info)----{}

字典的遍历

遍历key值

dict ={'name':'zhangsan','sex':'m'}
for key in dict.keys():
    print(key)
    
-----结果
name
sex

遍历value值

dict ={'name':'zhangsan','sex':'m'}
for value in dict.values():
    print(value)
    
---------   
zhangsan
m

遍历字典的项

dict ={'name':'zhangsan','sex':'m'}
for item in dict.items():
    print(item)
    
-------
('name', 'zhangsan')
('sex', 'm')

遍历字典的key-value(键值对)

dict ={'name':'zhangsan','sex':'m'}
for key,value in dict.items():
    print("key=%s,value=%s"%(key,value))
    
-------
key=name,value=zhangsan
key=sex,value=m
person = {'name': 'zhangsan', 'age': 18, 'x': 'y'}
for k,v in person.items():
    print(k,'=',v)
    
------
name = zhangsan
age = 18
x = y


习题

1有一个字典dict1 = {"a":100,"b":200,"c":300},使用代码,将字典的key和value互换,变成 {100:"a",200:"b",300:"c"}.

dict1 = {"a": 100, "b": 200, "c": 300}
dict2 ={v: k for k, v in dict1.items()}
print(dict2)

------
{100: 'a', 200: 'b', 300: 'c'}

2

chars=['a','c','x','r','x','d','p','a','c']
char_count={}

for char in chars:
    if char not in char_count:
        char_count[char]=chars.count(char)
vs=char_count.values()
max_count=max(vs)
for k,v in char_count.items():
    if v == max_count:
        print(k)
        
--------
a
c
x

3输入一个名字若不存在则加入,存在则显示存在

persons=[
    {'name':'zhangsan','age':18},
    {'name':'lisi','age':21},
    {'name':'wangwu','age':25},
    {'name':'zhaoliu','age':30}
]
x=input('输入姓名:')
for person in persons:
    if person['name'] == x:
        print('您输入的名字存在')
        break
else:
    new_person={'name': x}
    y=int(input('输入年龄:'))
    new_person['age']=y
    					------把新的数据存储到persons列表
    persons.append(new_person)
    print('用户添加成功')
print(persons)

集合

# {} 有两种意思: 字典、集合
# {} 里如果放的是键值对,它就是一个字典;如果 {} 放的是单个的值,就是一个集合
# 如果有重复的数据,会自动去除

集合的使用

set

----集合(set)是一个无序的不重复元素序列,可以使用大括号 { } 或者 set() 函数创建集合

---创建一个空集合必须用set()而不是{}

格式

parame = {value01,value02,...}
或者
set(value)

添加元素

-----将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作
thiset=set(("google","runoob","taobao"))
thiset.add("Facebook")
thiset.add("taobao")
print(thiset)

-----
{'Facebook', 'runoob', 'google', 'taobao'}
------x 可以有多个,用逗号分开
thiset=set(("google","runoob","taobao"))
thiset.update({1,3})
print(thiset)

thiset.update([1,4],[5,6])
print(thiset)

-----
{1, 3, 'taobao', 'google', 'runoob'}
{1, 3, 'taobao', 4, 5, 6, 'google', 'runoob'}

删除元素

remove

thiset=set(("google","runoob","taobao"))
thiset.remove("taobao")		---若删除不存在的则报错
print(thiset)
----
{'runoob', 'google'}

discard

thiset=set(("google","runoob","taobao"))
thiset.discard("taobao")
print(thiset)
-----
{'google', 'runoob'}

pop

随机删除

thiset=set(("google","runoob","taobao"))
x=thiset.pop()
print(x)
print(thiset)

----
google
{'runoob', 'taobao'}

运算符

first = {'李白', '白居易', '李清照', '杜甫', '王昌龄', '王维', '孟浩然', '王安石'}
second = {'李商隐', '杜甫', '李白', '白居易', '岑参', '王昌龄'}

# set 支持很多算数运算符
# print(first + second)
print(first - second)  # A - B 求A和B的 差集
print(second - first)
print(first & second)  # A & B 求A和B的 交集
print(first | second)  # A | B 求A和B的 并集
print(first ^ second)  # A ^ B 求A和B差集的并集

set常见方法列表

方法 描述
add() 为集合添加元素
clear() 移除集合中的所有元素
copy() 拷贝一个集合
pop() 随机移除元素
remove() 移除指定元素
union 返回两个集合的并集
update() 给集合添加元素
difference() 返回多个集合的差集
difference_update() 移除集合中的元素,该元素在指定的集合也存在。
discard() 删除集合中指定的元素
intersection() 返回集合的交集
intersection_update() 删除集合中的元素,该元素在指定的集合中不存在。
isdisjoint() 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
issubset() 判断指定集合是否为该方法参数集合的子集。
issuperset() 判断该方法的参数集合是否为指定集合的子集
symmetric_difference() 返回两个集合中不重复的元素集合。
symmetric_difference_update() 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。


练习

1有一个无序且元素数据重复的列表nums, nums=[5,8,7,6,4,1,3,5,1,8,4],要求对这个列表里的元素去重,并进行降序排序。

nums=[5,8,7,6,4,1,3,5,1,8,4]
nums2=list(set(nums))
nums2.sort(reverse=True)
print(nums2)

-------
[8, 7, 6, 5, 4, 3, 1]
nums=[5,8,7,6,4,1,3,5,1,8,4]
print(sorted(list(set(nums)),reverse=True))

-----
[8, 7, 6, 5, 4, 3, 1]

转换相关

内置类

nums=[9,8,45,3,5]
x=tuple(nums)	#使用tuple内置类转换为元组
print(x)-----(9, 8, 45, 3, 5)


y=set(nums)		#使用set内置类转换为集合
print(y)----{3, 5, 8, 9, 45}

z=list({'name':'zhangsan','age':18,'score':98})
print(z)----['name', 'age', 'score']

内置函数eval

----可执行字符串里的代码

a='1+1'
print(a)---------1+1	
print(eval(a))----2

转换为字符串

---JSON是一种轻量级的数据交换格式,JSON本质是一个字符串

json的dumps方法

----可以将字典、列表或者元组转换成为字符串

import  json
person ={'name':'zhangsan','age':18}	----字典
x=json.dumps(person)
print(x)
print(type(x))
-------
{"name": "zhangsan", "age": 18}
<class 'str'>


nums=[1,8,9,3,0]		-----列表
y=json.dumps(nums)
print(y)
print(type(y))
--------
[1, 8, 9, 3, 0]
<class 'str'>


words=('hello','good','yes')	----元组
z=json.dumps(words)
print(z)
print(type(z))
-------
["hello", "good", "yes"]
<class 'str'>

json的loads方法

-----可以将格式正确的字符串转换成为字典、列表

import  json

x='{"name":"zhangsan","age":18}'
person=json.loads(x)
print(person)
print(type(person))

-------
{'name': 'zhangsan', 'age': 18}
<class 'dict'>

y='[1,9,0,4,7]'
nums=json.loads(y)
print(nums)
print(type(nums))
--------
[1, 9, 0, 4, 7]
<class 'list'>

公共方法

print('hello' + 'word') - ----helloword

print(('good', 'yes') + ('hi', 'ok')) - -----('good', 'yes', 'hi', 'ok')

print({1, 2, 3} - {3})-----{1, 2}

print('hello' * 3)------hellohellohello

print([1, 2, 3] * 3)-----[1, 2, 3, 1, 2, 3, 1, 2, 3]

print((1, 2, 3) * 3)-----(1, 2, 3, 1, 2, 3, 1, 2, 3)
print('a' in 'abc')------True

print('d' in 'abc')-----False

print(1 in [1, 2, 3])-----True

print(3 in [6, 4, 5])-----False

print('zhangsan' in {'name': 'zhangsan', 'age': 18})----False
print('name' in {'name': 'zhangsan', 'age': 18, 'height': '180cm'})----True

print(3 in {3, 4, 5})----True
nums = (19, 82, 39, 12, 34, 58)

for i, e in enumerate(nums):
    print('第%d个数据是%d' % (i, e))

--------
第0个数据是19
第1个数据是82
第2个数据是39
第3个数据是12
第4个数据是34
第5个数据是58

person = {'name': 'zhangsan', 'age': 18, 'height': '180cm'}
for i, k in enumerate(person):
    print(i, k)
------
0 name
1 age
2 height

作业讲解代码

1

students = [
    {'name': '张三', 'age': 18, 'score': 52, 'tel': '1388888998', 'gender': 'female'},
    {'name': '李四', 'age': 28, 'score': 89, 'tel': '1388666666', 'gender': 'male'},
    {'name': '王五', 'age': 21, 'score': 95, 'tel': '1365588889', 'gender': 'unknown'},
    {'name': 'jerry', 'age': 20, 'score': 90, 'tel': '156666789', 'gender': 'unknown'},
    {'name': 'chris', 'age': 17, 'score': 98, 'tel': '13777775523', 'gender': 'male'},
    {'name': 'jack', 'age': 23, 'score': 52, 'tel': '13999999928', 'gender': 'female'},
    {'name': 'tony', 'age': 15, 'score': 98, 'tel': '1388888888', 'gender': 'unknown'}
]
# (1) 统计不及格学生的个数
# (2) 打印不及格学生的名字和对应的成绩
# (3) 统计未成年学生的个数
# (4) 打印手机尾号是8的学生的名字
# (5) 打印最高分和对应的学生的名字

#--------
count = 0
teenager_count = 0
max_score = students[0]['score']  # 假设第0个学生的成绩是最高分
for i, student in enumerate(students):
    if student['score'] < 60:
        count += 1
        print('%s不及格,分数%d' % (student['name'], student['score']))
    if student['age'] < 18:
        teenager_count += 1
    if student['tel'][-1] == '8':
        print('%s的手机以8结尾' % student['name'])

    if student['score'] > max_score:
        max_scount = student['score']

print('不及格的学生有%d个' % count)
print('未成年的学生有%d个' % teenager_count)
print('最高成绩时%d' % max_scount)

for student in students:
    if student['score'] == max_score:
        print('最高分是%s' % student['name'])

# ----------------------------------
# (6) 删除性别不明的所有学生
# 方法一,将不需要删除的数据添加到新列表
new_students = [x for x in students if x['gender'] != 'unknow']
print(new_students)

# 方法二,使用for循环倒着删除要删除的数据,避免“坑”
i = 0
for i in range(len(students) - 1, -1, -1):
    if students[i]['gender'] == 'unknown':
        students.remove(students[i])
print(students)

# 方法三,使用while循环删除需要删除的数据
i = 0
while i < len(students):
    if students[i]['gender'] == 'unknown':
        students.remove(students[i])
        i -= 1
    i += 1
print(students)

# 方法四,遍历在新的列表操作,删除是在原来的列表操作
i = 0
for student in students[:]:
    if student['gender'] == 'unknown':
        students.remove(student)
print(students)

# 方法五,使用内建函数filter()和匿名函数

new_students = filter(lambda x: x['gender'] != 'unknow', students)
print(list(new_students))
print('------------')

# (7) 将列表按学生成绩从大到小排序(选做)
for j in range(0, len(students) - 1):
    for i in range(0, len(students) - 1 - j):
        if students[i]['score'] < students[i + 1]['score']:
            students[i], students[i + 1] = students[i + 1], students[i]
print(students)


2

sing = ('李白', '白居易', '李清照', '杜甫', '王昌龄', '王维', '孟浩然', '王安石')
dance = ('李商隐', '杜甫', '李白', '白居易', '岑参', '王昌龄')
rap = ('李清照', '刘禹锡', '岑参', '王昌龄', '苏轼', '王维', '李白')
# (1) 求选课学生总共有多少人
# 去重
total = set(sing + dance + rap) #元组之间支持加法运算
print(len(total))

# (2) 求只选了第一个学科的人的数量和对应的名字
sing_only = []
for p in sing:
    if p not in dance and p not in rap:
        sing_only.append(p)
print('只选第一个学科的有{}人,是{}'.format(len(sing_only), sing_only))

# (3) 求只选了一门学科的学生的数量和对应的名字
# (4) 求只选了两门学科的学生的数量和对应的名字
# (5) 求只选了三门学生的学生的数量和对应的名字
p_dict = {}
all_persons = sing + dance + rap
print(all_persons)

for name in all_persons:
    if name not in p_dict:
        p_dict[name] = all_persons.count(name)
print(p_dict)

for k, v in p_dict.items():
    if v == 1:
        print('报了一门的有',k)
    elif v == 2:
        print('报了两门的有',k)
    elif v == 3:
        print('报了三门的有',k)
posted @ 2026-01-07 23:16  idazhi  阅读(5)  评论(0)    收藏  举报