极简美学——python

# 检查两个字符串的组成元素是不是一样的
from collections import Counter
def similarConsistence(first, second):
    return Counter(first) == Counter(second)
print(similarConsistence('abbc', 'cba'))  # False

# 内存占用
import sys
variable = 3
print(sys.getsizeof(variable))  # 28, 单位为bytes

# 大写第一个字母
print('hello'.title())

# 列表分块
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)))))
print(chunk([1, 2, 3, 4, 5], 2))  # [[1, 2], [3, 4], [5]]

# filter()
def is_odd(n):
    return n % 2 == 1
print(list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))) # [1, 3, 5, 7, 9]

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

# 列表展开
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
print(deep_flatten([1, [2], [[3], 4], 5])) # [1,2,3,4,5]

# 列表的差
print(set([1, 2, 3]).difference(set([1, 2]))) # {3}

# 合并字典
def merge_dictionaries(a, b):
    return {**a, **b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值