分享

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

 bdpqlxz 2020-09-05

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)

点击加载图片

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多