print("Sample counts per class:\n{}".format(
{n: v for n, v in zip(cancer.target_names, np.bincount(cancer.target))}))
中的 n:v for n,v in zip() 这句语法怎么理解
尤其是其中的 n:v 这里
print("Sample counts per class:\n{}".format(
{n: v for n, v in zip(cancer.target_names, np.bincount(cancer.target))}))
中的 n:v for n,v in zip() 这句语法怎么理解
尤其是其中的 n:v 这里
zip(list1,list2)是返回一个迭代对象, 每次迭代时会同时读取list1,list2两个列表中的各个元素打包成一个元组,
元组中有两个元素分别是list1,list2两个列表中相同下标的元素,比如:
list1 = ["key1","key2","key3"]
list2 = ["value1","value2","value3"]
print(list( zip(list1,list2)))
结果为
[('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')]
d = {n:v for n,v in zip(list1,list2)}
是字典生成式,遍历zip(list1,list2)返回的迭代对象,
每次遍历将之前打包成的元组中的两个元素拆开分别赋值给n和v,
n:v是用n做为字典的键,用v做为字典的值,生成字典。
d的结果为
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}