900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > UC头条:必须掌握的Python技巧

UC头条:必须掌握的Python技巧

时间:2020-06-14 15:50:46

相关推荐

UC头条:必须掌握的Python技巧

9、展开列表

10、交换两个变量的值的函数

11、字典默认值

1、合并两个字典

方法一:

defmerge_two_dicts(a, b): c = a.copy# make a copy of a c.update(b)# modify keys and values of a with the once from breturn c

a ={"x":1,"y":14} b ={"y":314,"z":5,"a":2,"b":"0"} v1 = merge_two_dicts(a,b)print(v1)

点击加载图片

方法二:

defmerge_dictionaries(a, b):return{**a,**b} a ={"x":1,"y":2} b ={"y":3,"z":4}print(merge_dictionaries(a, b))

点击加载图片

2、将两个列表转化为字典(zip方法)

defto_dictionary(keys, values):returndict(zip(keys, values)) keys =["l","o","v","e"] values =[9,4,2,0]print(to_dictionary(keys, values))

点击加载图片

3、枚举法遍历字典的索引与值

list=["a","b","c","d"]for index, element inenumerate(list):print("Value", element,"Index ", index,)

点击加载图片

4、Try可以加else:如果没有引起异常,就会执行else语句

try:print(2*3)except TypeError:print("An exception was raised")else:print("Thank God, no exceptions were raised.")

点击加载图片

5、根据元素出现频率取最常见的元素

defmost_frequent(li):returnmax(set(li), key = li.count) li =[1,2,1,2,3,2,1,4,2] v1 = most_frequent(li)print(v1)

点击加载图片

6、回文序列:检查给定的字符串是不是回文序列

回文:就是正读反读都是一样的序列;

它首先会把所有字母转化为小写,并移除非英文字母符号;

最后,它会对比字符串与反向字符串是否相等,相等则表示为回文序列。

defpalindrome(string):from re import sub

s = sub("[\W_]","", string.lower)return s == s[::-1] v1 = palindrome("I love u evol I")print(v1)

点击加载图片

7、不使用if,else的计算子

不使用条件语句就实现加减乘除、求幂操作;

通过字典来操作

import operator

action ={"+": operator.add,"-": operator.sub,"/": operator.truediv,"*": operator.mul,"**":pow} v1 = action["-"](52392,51872)print(v1)

点击加载图片

8、列表重组顺序

该算法会打乱列表元素的顺序,它主要会通过 Fisher-Yates 算法对新列表进行排序

from copy import deepcopy from random import randint defshuffle(lst): temp_lst = deepcopy(lst) m =len(temp_lst)while(m): m -=1 i = randint(0, m) temp_lst[m], temp_lst[i]= temp_lst[i], temp_lst[m]return temp_lst

foo =[1,2,3,4,5] foo2 =[3,4,6,2,8,43,100,43,2] v1 = shuffle(foo) v2 = shuffle(foo2)print(v1, v2, sep="\n")

点击加载图片

9、展开列表

将列表内的所有元素,包括子列表,都展开成一个列表

defspread(arg): ret =[]for i in arg:ifisinstance(i,list): ret.extend(i)else: ret.append(i)return ret

v1 = spread([1,2,3,[4,5,6],[7],8,9])print(v1)

点击加载图片

10、交换两个变量的值的函数

defswap(a, b):return b, a

a, b =-1,14 v1 = swap(a, b)print(v1)

点击加载图片

11、字典默认值

通过 Key 取对应的 Value 值,可以通过以下方式设置默认值;

如果 get 方法没有设置默认值,那么如果遇到不存在的 Key,则会返回 None

d ={"a":1,"b":2} v1 = d.get("c",3)print(v1)

点击加载图片

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。