lmp5023

1.移除字典点键值(key/value)对

test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} 
  
# 输出原始的字典
print ("字典移除前 : " + str(test_dict)) 
#如果key!=\'Zhihu\',则输出键值对字典 new_dict = {key:val for key, val in test_dict.items() if key != \'Zhihu\'} # 输出移除后的字典 print ("字典移除后 : " + str(new_dict))

字典移除前:{\'Runoob\':1,\'Google\':2,\'Taobao\':3,\'Zhihu\':4}

字典移除后:{\'Runoob\':1,\'Google\':2,\'Taobao\':3} 

 

2.合并字典

def Merge(dict1, dict2): 
    res = {**dict1, **dict2} 
    return res 
      
# 两个字典
dict1 = {\'a\': 10, \'b\': 8} 
dict2 = {\'d\': 6, \'c\': 4} 
dict3 = Merge(dict1, dict2) 
print(dict3)

  

执行以上代码输出结果为:

{\'a\': 10, \'b\': 8, \'d\': 6, \'c\': 4}

Python中的*与**操作符使用最多的就是两种用法。
1.用做运算符,即*表示乘号,**表示次方。
2.用于指定函数传入参数的类型的。*用于参数前面,表示传入的多个参数将按照元组的形式存储,是一个元组;
**用于参数前则表示传入的(多个)参数将按照字典的形式存储,是一个字典。

 

3.按键(key)或值(value)对字典进行排序

print ((i, key_value[i]), end =" ")

end=“ ”是设置print()打印结束添加的字符。 默认是end=“\n”,也就是打印完,以换行符结尾。

lambda存在意义就是对简单函数的简洁表示

比如函数f:

def f(x):
    return x**2

可以写成:

f = lambda x:x**2

4.__name__==\'__main__\'

__name__ 是当前模块名,当模块被直接运行时模块名为 __main__ 。这句话的意思就是,当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。

分类:

技术点:

相关文章:

  • 2022-02-15
  • 2022-12-23
  • 2021-09-19
  • 2022-01-05
  • 2021-07-04
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-11-08
相关资源
相似解决方案