table of Contents
- Del difference and pop on the delete list elements
- Sort the list with a lambda expression
- What type of data dictionary key support
- Using a microtome type of object generator
- The cycle produces a list generator becomes
- How Python dictionaries with JSON string Huzhuan
Difference 11.del and pop on the delete list elements
13. sort the list with a lambda expression
a =[
{'name': 'Bill', 'age': 40},
{'name': 'Mike', 'age': 10},
{'name': 'John', 'age': 20}
]
print(sorted(a, key=lambda x:x['age']))
[{'name': 'Mike', 'age': 10}, {'name': 'John', 'age': 20}, {'name': 'Bill', 'age': 40}]
a.sort(key=lambda x:x['age'], reverse= True)
print(a)
[{'name': 'Bill', 'age': 40}, {'name': 'John', 'age': 20}, {'name': 'Mike', 'age': 10}]
to sum up
13. What type of data dictionary key support
Lists and dictionaries can not be used as key
Because the key is not changed, but the values are lists and dictionaries can change, once the changes could not find the corresponding value
14. Use of a slice type of object generator
from itertools import islice
gen = iter(range(10))
print(type(gen))
for i in islice(gen, 2, 6):
print(i, end=' ')
to sum up
15. The list generator into the generated cycle
a = [i for i in range(10)]
print(a) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(a)) # <class 'list'>
b = (i for i in range(10))
print(type(b)) # <class 'generator'>
for i in b:
print(i, end=' ')
# 0 1 2 3 4 5 6 7 8 9
x = (1, 2, 3, 4)
print(type(x)) # <class 'tuple'>
Summary
not for, it will become a tuple
16.Python dictionary and how JSON string Huzhuan
import json
a = {'a': 1, 'b': '2', 'c': 'x'}
print(a) # {'a': 1, 'b': '2', 'c': 'x'}
print(type(a)) # <class 'dict'>
json_str = json.dumps(a)
print(json_str) # {"a": 1, "b": "2", "c": "x"}
print(type(json_str)) # <class 'str'>
a1 = json.loads(json_str)
print(a1) # {'a': 1, 'b': '2', 'c': 'x'}
print(type(a1)) # <class 'dict'>
to sum up