Python tips and tricks-30 lines of code block to take you to experience the short and powerful Python (continuous update)

# 1. 重复元素判定
def all_unique(lst):
    return len(lst)== len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True

# 2. 字符串组成是否相同
from collections import Counter
def anagram(first, second):
    return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True

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

# 4. 压缩列表
def compact(lst):
    return list(filter(bool, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34])
# [ 1, 2, 3, 'a', 's', 34 ]

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

# 6. 逗号连接
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))

# 7. 元音统计
import re
def count_vowels(str):
    return len(re.findall(r'[aeiou]', str, re.IGNORECASE))
count_vowels('foobar') # 3
count_vowels('gym') # 0

# 8. 递归展开列表
def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i) # extend和append的区别在于extend会去掉一层括号
        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
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]

# 9. 列表的差
def difference(a, b):
    set_a = set(a)
    set_b = set(b)
    comparison = set_a.difference(set_b)
    return list(comparison)
difference([1,2,3], [1,2,4]) # [3]

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

# 11. 将列表转换为字典
def to_dictionary(keys,values):
    return dict(zip(keys,values))
keys =['a','b']
values = [1,2]
to_dictionary(keys,values)

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

# 13. 回文序列
def palindrome(string):
    from re import sub
    s = sub('[\W_]', '', string.lower())
    return s == s[::-1]
palindrome('taco cat') # True

# 14. 不使用if_else运算语句
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25

 

Guess you like

Origin blog.csdn.net/weixin_40539952/article/details/108586619