面对洋洋洒洒的知识点,我往往 “一看就会,一写就废”,为了更有针对性的加深知识点的印象,我将以做题的形式继续总结 Python 系列,每篇 10 道问答,以下是本篇目录:
Python 系列总结都是我自己平时的学习笔记,如果有不正确的地方,希望各位佬儿哥指正纠偏
staff = {'Data Scientist': 'Mike', 'Django Developer': 'Dylan'}
答:
staff = {'Data Scientist': 'Mike', 'Django Developer': 'Dylan'}
# 我的笨方法
reverse = {}
for k, v in staff.items():
reverse[v] = k
print(reverse)
# 标答给的方法(字典推导式)
inverted_staff = {v: k for k, v in staff.items()}
print(inverted_staff)
l = [[1, 2, 3], [4, 5], [6], [7, 8], [9]]
答:
# 针对此题目,我想到的是循环遍历
result = []
for i in l:
for n in i:
result.append(n)
print(result)
# 标答给的方法1:
# 在 sum() 函数中使用的第二个参数是空列表,表示从空列表开始计算和。
merged_list = sum(l, [])
print(merged_list)
# 标答给的方法2:列表推导式
merged_list = [item for sublist in l for item in sublist]
print(merged_list)
# 可如上3个方法只能针对此题目,一旦题目列表没这么规范,比如下面的列表,那么如上3个方法就无法实现
l = [0, [1, 2, [3]], [4, 5], [6], [7, 8], [9]]
# 能够同时解决如上问题的方法是使用递归函数
def flatten_list(l):
flat_list = []
for item in l:
if type(item) == list:
flat_list.extend(flatten_list(item))
else:
flat_list.append(item)
return flat_list
print(flatten_list(l))
答:
l = ['1', '2', '3']
l1 = [int(i) for i in l]
print(l1)
l2 = ['1', 2, '3.0', 4.0, '5', 6]
l3 = [float(i) for i in l2]
print(l3)
cars = ['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']
答:
cars = ['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']
d = dict.fromkeys(cars, 0)
print(d)
['a', 'a', 'b', 'a', 'c']
答:
l = ['a', 'a', 'b', 'a', 'c']
l1 = list(set(l))
print(l1)
cars = ['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']
答:
cars = ['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']
# 我想到的是列表推导式
l = [i for i in cars if i == 'Volvo']
print(l)
# 标答使用filter
l2 = filter(lambda car: car == 'Volvo', cars)
print(list(l2))
# filter 函数在 Python 中返回一个过滤器对象,它是一个迭代器,所以想打印值需要使用list()
numbers = [55, -30, 28, -36, 48, 20]
cars = ['Ford', 'Tesla', 'BMW', 'Volvo', 'Audi']
答:
numbers.sort()
print(numbers)
cars.sort()
print(cars)
set1 = {"1", "2", "5"}
set2 = {"4", "6", "7"}
答:
set1.update(set2)
print(set1)
d = {'one': 1, 'three': 4, 'five': 8, 'six': 10, 'two': 2}
答:
sorted_dict = sorted(d.items(), key=lambda x: x[0])
print(sorted_dict)
d = {'one': 1, 'three': 4, 'five': 8, 'six': 10, 'two': 2}
答:
sorted_dict = sorted(d.items(), key=lambda x: x[1])
print(sorted_dict)