前言

在基于Python而做的接口自动化测试及web平台开发相关工作,会出现不少重复使用到的功能,如:计费的小数点后两位(不进行四舍五入)、字典剔除、数组合并、字典转数组等,本文收集了一些常用方法。

 

例子

1. 判定重复元素

使用 set() 函数来检查列表是不是存在重复元素,它会移除所有重复元素。

def all_unique(lst):
 return len(lst) == len(set(lst))

if __name__ == "__main__":
    x = [1, 1, 2, 1, 2, 3, 2, 3, 4, 5, 6]
    y = [1, 2, 3, 4, 5]
    aux = all_unique(x) 
    auy = all_unique(y) 
    print(aux)
    print(auy)

 

2. 判定字符元素组成

使用 set() 函数来检查两个字符串的元素组成是不是一样的。

def all_unique(lst):
 return len(lst) == len(set(lst))

if __name__ == "__main__":
    x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]
    y = [1, 2, 3, 4, 5]
    aux = all_unique(x) 
    auy = all_unique(y)
    print(aux)
    print(auy)

 

3. 内存占用

下面代码块可以检查变量所占用的内存。

from collections import Counter
def anagram(first, second):
 return Counter(first) == Counter(second)

if __name__ == "__main__":
    res = anagram("abcd3", "3acdb") 
    print(res)

 

4. 字节占用

这个可以检查字符串占用的字节数。

def byte_size(string):
 return(len(string.encode('utf-8')))

if __name__ == "__main__":
    empty = byte_size("打印 N 次字符串")
    HW = byte_size('Hello World')
    print(empty)
    print(HW)

 

5. 重复打印字符串 N 次

该代码块不需要循环语句就能重复打印字符串 N 次。

n = 2
s ="Programming"
print(s * n)

 

6. 第一个字母大写

使用 title() 方法使字符串中每一个单词的首字母变成大写。

s = "programming is awesome"
print(s.title())

 

7. 分块

制定一个长度,按照这个长度切割列表。

from math import ceil
def chunk(lst, size):
 return list(
 map(lambda x: lst[x * size:x * size + size],
 list(range(0, ceil(len(lst) / size)))))

if __name__ == "__main__":
    res = chunk([1, 2, 3, 4, 5], 2)
    print(res)

 

8. 压缩

使用 filter() 函数将布尔型的值去掉,例如(False,None,0,“”)。

def compact(lst):
 return list(filter(bool, lst))

if __name__ == "__main__":
    res = compact([0, 1, False, 2, '', 3, 'a', 's', 34])
    print(res)

 

9. 解包

下面代码块可以将打包好的成对列表,解压成两组不同的元组。

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(list(transposed))

 

10. 链式对比

在一行代码中使用不同的运算符对比多个不同的元素。

a = 3
print(2 < a < 8)
print(1 == a < 2)

 

11. 逗号连接

可以将列表组合成字符串,每一个元素间的分隔方式设置为逗号。

hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))

 

12. 首字母小写

使用下面代码使字符串中单词的首字母变成小写。

def decapitalize(string):
 return string[:1].lower() + string[1:]

if __name__ == "__main__":
    res1 = decapitalize('FooBar')
    res2 = decapitalize('FooBar')
    print(res1, res2)

 

13. 展开列表

通过递归的方式,将列表的嵌套展开为一个列表。

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

def deep_flatten(lst):
    result = []
    result.extend(
        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
    return result

if __name__ == "__main__":
    res = deep_flatten([1, [2], [[3], 4], 5]) 
    print(res)

 

14. 列表的差

下面代码块将返回第一个列表有,第二个列表没有的元素。

如果同时要反馈第二个列表独有的元素,还需要加一句 set_b.difference(set_a)。

def difference(a, b):
 set_a = set(a)
 set_b = set(b)
 comparison = set_a.difference(set_b)
 return list(comparison)

if __name__ == "__main__":
    res = difference([1, 2, 4, 6], [1, 2, 4, 5])
    print(res)

 

15. 通过函数取差

首先会使用一个自定义函数,然后再返回函数后结果有差别的列表元素。

def difference_by(a, b, fn):
    b = set(map(fn, b))
    return [item for item in a if fn(item) not in b]

if __name__ == "__main__":
    from math import floor
    dl = difference_by([2.1, 1.2], [2.3, 3.4], floor)
    dd = difference_by([{'x': 2}, {'x': 1}], [{'x': 1}], lambda v: v['x'])
    print(dl)
    print(dd)

 

16. 链式函数调用

可以在一行代码内调用多个函数。

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b


if __name__ == "__main__":
    a, b = 4, 5
    print((subtract if a > b else add)(a, b))

 

17. 检查重复项

检查两个列表是否有重复元素。

def has_duplicates(lst):
    return len(lst) != len(set(lst))

if __name__ == "__main__":
    x = [1, 2, 3, 4, 5, 5]
    y = [1, 2, 3, 4, 5]
    res1 = has_duplicates(x)
    res2 = has_duplicates(y)
    print(res1)
    print(res2)

 

18. 合并两个字典

合并两个字典的方法。

def merge_dictionaries(a, b):
    return {**a, **b}


if __name__ == "__main__":
    a = {'x': 1, 'y': 2}
    b = {'y': 3, 'z': 4}
    print(merge_dictionaries(a, b))

 

19. 将两个列表转化为字典

把两个列表,转化为有对应关系的字典,注意key和value的关系

def to_dictionary(keys, values):
    return dict(zip(keys, values))


if __name__ == "__main__":
    keys = ["a", "b", "c"]
    values = [2, 3, 4]
    print(to_dictionary(keys, values))

 

20. 使用枚举

使用for来枚举列表的索引与值。

lists = ["a", "b", "c", "d"]

for index, element in enumerate(lists):
    print("Value", element, "Index ", index, )

 

22. 执行时间

计算执行特定代码所花费的时间。

import time

__all__ = ['print_time']


def print_time(f):

    def fi(*args, **kwargs):
        s = time.time()
        res = f(*args, **kwargs)
        print('--> RUN TIME: <%s> : %s' % (f.__name__, time.time() - s))
        return res

    return fi


# test
@print_time
def _test1():
    time.sleep(1)
    print('work is running')


if __name__ == '__main__':
    _test1()
22.Try else
使用 try/except 语句的时候,可以加一个 else 子句,没有触发错误的话,else代码就会被运行。

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

 

23. 元素频率

根据元素的出现频率取列表中最常见的元素。

def most_frequent(list):
    return max(set(list), key=list.count)


if __name__ == '__main__':
    lists = [1, 2, 1, 2, 3, 2, 1, 4, 2]
    res = most_frequent(lists)
    print(res)

 

24. 回文序列

检查字符串是不是回文序列,会先把所有字母转化为小写,并移除非英文字母符号。然后,对比字符串与反向字符串是否相等,相等则返回true。

def palindrome(string):
    from re import sub
    s = sub('[\W_]', '', string.lower())
    return s == s[::-1]


if __name__ == '__main__':
    res = palindrome('taco cat')
    print(res)

 

25. 不使用 if-else 的计算子

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

import operator
action = {
 "+": operator.add,
 "-": operator.sub,
 "/": operator.truediv,
 "*": operator.mul,
 "**": pow
}

print(action['+'](50, 25))
print(action['-'](50, 25))
print(action['/'](50, 25))
print(action['*'](50, 25))
print(action['**'](2, 8))

 

26.Shuffle

打乱列表元素的顺序,通过 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


if __name__ == '__main__':
    foo = [1, 2, 3]
    res = shuffle(foo)
    print(res)

 

27. 展开列表

将列表中所有元素展开成一个列表。

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

if __name__ == '__main__':
    res = spread([1,2,3,[4,5,6],[7],8,9])
    print(res)

 

28. 交换值

快捷交换两个变量的值。

def swap(a, b):
    return b, a


if __name__ == '__main__':
    a, b = -1, 14
    res = swap(a, b)
    print(res)

 

29. 字典默认值

通过 Key 取对应的 Value 值,通过下面代码块设置默认值。

如果 get() 方法没有设置默认值,遇到不存在的 Key时会返回 None。

d = {'a': 1, 'b': 2}

print(d.get('c'))
print(d.get('c', 3))
print(d)