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)
name.add("liuziheng")
print(name)
name.clear()
print(name)
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 = {
'李商隐','杜甫','李白','白居易','岑参','王昌龄'}
print(first - second)
print(second-first)
print(first & second)
print(first | second)
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)
- json: the essence of json is a string
- json can convert lists, tuples, dictionaries, etc. into json strings
import json
person = {
'name':'zhangsan','age':'18','gender':'female'}
m = json.dumps(person)
print(m)
print(type(m))
n = '{"name": "zhangsan", "age": "18", "gender": "female"}'
p = eval(n)
print(p)
print(type(p))
s = json.loads(n)
print(s)
print(type(s))