必须掌握的Python技巧(三)

1、合并两个字典

  • 方法一:
def merge_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 b
    return c
a = {'x':1,'y':14}
b = {'y':314,'z':5, 'a':2, 'b':'0'}
v1 = merge_two_dicts(a,b)
print(v1)

11

  • 方法二:
def merge_dictionaries(a, b):
    return {**a, **b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b))

22


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

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

33


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

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

44


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

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

55


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

def most_frequent(li):
    return max(set(li), key = li.count)
li = [1,2,1,2,3,2,1,4,2]
v1 = most_frequent(li)
print(v1)

66


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

回文:就是正读反读都是一样的序列;
它首先会把所有字母转化为小写,并移除非英文字母符号;
最后,它会对比字符串与反向字符串是否相等,相等则表示为回文序列。

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

77


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

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

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

88


8、列表重组顺序

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

from copy import deepcopy
from random import randint
def shuffle(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')

99

9、展开列表

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

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(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


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

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

110


11、字典默认值

通过 Key 取对应的 Value 值,可以通过以下方式设置默认值;
如果 get() 方法没有设置默认值,那么如果遇到不存在的 Key,则会返回 None

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

122

猜你喜欢

转载自blog.csdn.net/Viewinfinitely/article/details/108040326