Python interview one hundred questions - lists, tuples and dictionaries (2)

table of Contents

  1. Del difference and pop on the delete list elements
  2. Sort the list with a lambda expression
  3. What type of data dictionary key support
  4. Using a microtome type of object generator
  5. The cycle produces a list generator becomes
  6. How Python dictionaries with JSON string Huzhuan

Difference 11.del and pop on the delete list elements

Here Insert Picture Description

13. sort the list with a lambda expression

Here Insert Picture Description

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
Here Insert Picture Description

13. What type of data dictionary key support

Here Insert Picture Description
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

Here Insert Picture Description

from itertools import islice

gen = iter(range(10))
print(type(gen))

for i in islice(gen, 2, 6):
    print(i, end=' ')

to sum up
Here Insert Picture Description

15. The list generator into the generated cycle

Here Insert Picture Description

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
Here Insert Picture Description
not for, it will become a tuple

16.Python dictionary and how JSON string Huzhuan

Here Insert Picture Description

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
Here Insert Picture Description

Published 11 original articles · won praise 3 · Views 925

Guess you like

Origin blog.csdn.net/qq_36551226/article/details/104183035