一些面试题总结
合并字典:请合并下面两个字典 a = {"A":1,"B":2},b = {"C":3,"D":4} dict1 = {"A": 1, "B": 2} dict2 = {"C": 3, "D": 4} # 方式一 **表示打散 print({**dict1, **dict2}) # * ** 都表示打散可迭代对象 # 方式二 update方法 dict1.update(dict2) # 合并字典 元组操作:如何把元组 ("a","b") 和元组 (1,2),变为字典 {"a":1,"b":2} # zip的使用 a = ("a", "b") b = (1, 2) print(dict(zip(a, b))) 交换字典的键和值 dict1 = {"A": 1, "B": 2} res = {k: v for v, k in dict1.items()} print(res) 我们知道对于列表可以使用切片操作进行部分元素的选择,那么如何对生成器类型的对象实现相同的功能呢? Python交换两个变量的值 a,b=b,a 这个不是元组解包,在栈的顶端做两个值的交换。 read()/readline()/readlines() with open('test.txt', 'r', encoding='utf-8') as f: text = f.read() print(text) with