Python Basics-07 Collection

Use of collections

  • A collection is a non-repeating, unordered collection that can be represented by curly braces or set
  • {} has two meanings: dictionary; set
  • If you put a key-value pair in {}, it is a dictionary; if you put a single value in {}, it is a collection
person = {
    
    'name':'zhangsan','age':'18'}  # 字典
x = {
    
    'hello','good',18}  # 集合

# 集合有自动去重的功能
name = {
    
    'zhangsan','lisi','wangwu','zhangsan','jack','tony','lisi'}
print(name)  # {'wangwu', 'jack', 'lisi', 'tony', 'zhangsan'}

# set 可以进行增删改查的方法,但是不常用,add,pop(随机删除一个元素),remove(删除一个指定元素,没有就报错),clear(清空集合),union(将多个集合合并,生成一个新的集合),update(将一个集合拼接到指定的集合中)
name.add("liuziheng")  # 增加
print(name)  # {'jack', 'liuziheng', 'lisi', 'wangwu', 'zhangsan', 'tony'}

name.clear()  # 清空一个集合
print(name)  # set()  注意! 一个 {} 表示的是一个空字典,空集合用 set()来表示

Advanced use of collections

  • set supports many arithmetic operators
  • set does not support addition
  • - Subtraction can find the difference of two sets
  • & can find the intersection of two sets
first = {
    
    '李白','白居易','李清照','杜甫','王昌龄','王维','孟浩然','王安石'}
second = {
    
    '李商隐','杜甫','李白','白居易','岑参','王昌龄'}

# 求first和second的差集
print(first - second)  # {'王维', '王安石', '孟浩然', '李清照'} first有second没有
print(second-first)  # {'岑参', '李商隐'} second有first没有

# 求first和second的交集
print(first & second)  # {'王昌龄', '白居易', '杜甫', '李白'}

# 求first和second的并集
print(first | second)  # {'王维', '白居易', '李商隐', '王安石', '岑参', '孟浩然', '杜甫', '李白', '王昌龄', '李清照'}

# 求first和second的差集的并集,first有second没有加上second有first没有
print(first ^ second)  # {'李清照', '王维', '李商隐', '王安石', '岑参', '孟浩然'}

collection of exercises

  • Deduplicate and sort the following list
nums = [5,8,7,6,4,1,3,5,1,8,4]
nums = set(nums)
nums = list(nums)
nums.sort()
print(nums)
  • In Python, there is a built-in function that can execute code inside a string
  • eval
a = "print('this is a eval test')"
eval(a)  # this is a eval test
  • json: the essence of json is a string
  • json can convert lists, tuples, dictionaries, etc. into json strings
# json dumps loads
# python -> json
# 字符串 ->  字符串
# 字典  ->   对象
# 列表/元组/集合 -> 数组
import json
person = {
    
    'name':'zhangsan','age':'18','gender':'female'}
m = json.dumps(person)
print(m)
print(type(m))

# {"name": "zhangsan", "age": "18", "gender": "female"}
# <class 'str'>
# 转换后不能再像字典一样根据key查找value

# 如何把一个字符串变成字典
n = '{"name": "zhangsan", "age": "18", "gender": "female"}'
p = eval(n)
print(p)  # {'name': 'zhangsan', 'age': '18', 'gender': 'female'}
print(type(p))  # <class 'dict'>

s = json.loads(n)
print(s)  # {'name': 'zhangsan', 'age': '18', 'gender': 'female'}
print(type(s))  # <class 'dict'>

Supongo que te gusta

Origin blog.csdn.net/Lz__Heng/article/details/130192185
Recomendado
Clasificación