1.合并两个字典
# 可以使用**符号来解压字典
def Merge(dict1, dict2):
res = {**dict1, **dict2}
return res
# 两个字典
dict1 = {"name": "Joy", "age": 25}
dict2 = {"name": "Joy", "city": "New York"}
dict3 = Merge(dict1, dict2)
print(dict3)
输出
{'name': 'Joy', 'age': 25, 'city': 'New York'}
2.检查文件是否存在
from os import path
def check_for_file():
print("Does file exist:", path.exists("data.csv"))
if __name__ == "__main__":
check_for_file()
输出
Does file exist: False
3.查找出现次数最多的元素(使用max方法找出列表中出现次数最多的元素。)
def most_frequent(list):
return max(set(list), key=list.count)
mylist = [1, 1, 2, 3, 4, 5, 6, 6, 2, 2]
print("出现次数最多的元素是:", most_frequent(mylist))
输出
出现次数最多的元素是: 2
4.将两个列表转换为字典
def list_to_dictionary(keys, values):
return dict(zip(keys, values))
list1 = [1, 2, 3]
list2 = ['one', 'two', 'three']
print(list_to_dictionary(list1, list2))
输出
{1: 'one', 2: 'two', 3: 'three'}
5.统计字频
from collections import Counter
result = Counter('banana')
print(result)
输出
Counter({'a': 3, 'n': 2, 'b': 1})