python常用极简代码

1. 重复元素判定

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

1
2
3
4
5
6
7
8
9
10
11
#! /usr/bin/env python
# -*- coding: utf-8 -*-

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


x = [1, 1, 2, 3, 4, 5, 6, 4, 3, 2]
y = [1, 2, 3, 4, 5]
print(all_unique(x)) # False
print(all_unique(y)) # True

字符元素组成判定

检查两个字符串的组成元素是不是一样的。

1
2
3
4
5
6
7
from collections import Counter

def anagram(first, second):
return Counter(first) == Counter(second)


print(anagram("abcd3", "3acbd")) # True

内存占用

1
2
3
4
import sys

variable = 30
print(sys.getsizeof(variable)) # 28

字节占用

1
2
3
4
5
6
def byte_size(string):
return (len(string.encode("utf-8")))


print(byte_size('')) # 0
print(byte_size("Hello World")) # 11

打印N次字符串

1
2
3
n = 5
s = "HHHHHH "
print(s * n) # HHHHHH HHHHHH HHHHHH HHHHHH HHHHHH

大写第一个字母

1
2
s = "this is my blog"
print(s.title()) # This Is My Blog

分块

1
2
3
4
5
6
7
8
9
10
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)))))


ret = chunk([1, 2, 3, 4, 5], 2)
print(ret) # [[1, 2], [3, 4], [5]]

压缩

这个方法可以将布尔型的值去掉,例如(False,None,0,””),它使用 filter() 函数。

1
2
3
4
5
def compact(lst):
return list(filter(bool, lst))


print(compact([0, 1, False, 2, "", 3, "a", "s", 34])) # [1, 2, 3, 'a', 's', 34]

解包

1
2
3
array = [["a", "b"], ["c", "d"], ["e", "f"]]
transposed = zip(*array)
print(list(transposed)) # [('a', 'c', 'e'), ('b', 'd', 'f')]

链式对比

1
2
3
a = 3
print(2 < a < 8) # True
print(1 == a < 2) # False

逗号连接

下面的代码可以将列表连接成单个字符串,且每一个元素间的分隔方式设置为了逗号。

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

首字母小写

1
2
3
4
def decapitalize(str):
return str[:1].lower() + str[1:]

print(decapitalize("FooBar")) # fooBar

展开列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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]

列表的差集

该方法将返回第一个列表的元素,其不在第二个列表内。如果同时要反馈第二个列表独有的元素,还需要加一句 set_b.difference(set_a)

1
2
3
4
5
6
7
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)

print(difference([1, 2, 3], [1, 2, 4])) # [3]

如下方法首先会应用一个给定的函数,然后再返回应用函数后结果有差别的列表元素。

1
2
3
4
5
6
7
8
9
from math import floor

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


print(difference_by([2.1, 1.2], [2.3, 3.4], floor)) # [1.2]
print(difference_by([{'x': 2}, {'x': 1}], [{'x': 1}], lambda v: v['x'])) # [{'x': 2}]

链式函数调用

1
2
3
4
5
6
7
8
def add(a, b):
return a + b

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

a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9

检查重复项

1
2
3
4
5
6
7
8
9
def has_duplicates(lst):
return len(lst) != len(set(lst))


x = [1, 2, 3, 4, 5, 5]
y = [1, 2, 3, 4, 5]

print(has_duplicates(x)) # True
print(has_duplicates(y)) # False

合并两个字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def megre_two_dicts(a, b):
c = a.copy()
c.update(b)
return c


a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
print(megre_two_dicts(a, b)) # {'x': 1, 'y': 3, 'z': 4}

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


a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'x': 1, 'y': 3, 'z': 4}

将两个列表转化为字典

1
2
3
4
5
6
7
def to_dictionary(keys, values):
return dict(zip(keys, values))


keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'b': 3, 'c': 4}

使用枚举

1
2
3
4
5
6
7
8
list = ["a", "b", "c", "d"]
for index, element in enumerate(list):
print("Value", element, "Index ", index, )

# Value a Index 0
# Value b Index 1
# Value c Index 2
# Value d Index 3

执行时间

1
2
3
4
5
6
7
8
9
10
11
import time

start_time = time.time()
a = 1
b = 2
c = a + b
print(c) # 3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)
# Time: 2.6226043701171875e-06

Try else

1
2
3
4
5
6
7
8
try:
2 * 3
except TypeError:
print("An exception was raised")
else:
print("Thand God, no exceptions were raised.")

# Thand God, no exceptions were raised.

元素频率

1
2
3
4
5
6
def mode_frequent(list):
return max(set(list), key=list.count)


list = [1, 2, 3, 12, 4, 5, 6, 7, 23, 4, 5, 2]
print(mode_frequent(list)) # 2

回文序列

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

print(palindrome('taco cat')) # True

不使用 if-else 的计算子

1
2
3
4
5
6
7
8
9
10
import operator

action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25

Shuffle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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]
print(shuffle(foo)) # [1,2,3]

展开列表

1
2
3
4
5
6
7
8
9
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
# print(spread([1, 2, 3, [4, 5, 6], [7], 8, 9]))

字典默认值

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

本文标题:python常用极简代码

文章作者:shuke

发布时间:2020年07月26日 - 13:07

最后更新:2020年07月26日 - 17:07

原始链接:https://shuke163.github.io/2020/07/26/python%E5%B8%B8%E7%94%A8%E6%9E%81%E7%AE%80%E4%BB%A3%E7%A0%81/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------本文结束感谢您的阅读-------------

本文标题:python常用极简代码

文章作者:shuke

发布时间:2020年07月26日 - 13:07

最后更新:2020年07月26日 - 17:07

原始链接:https://shuke163.github.io/2020/07/26/python%E5%B8%B8%E7%94%A8%E6%9E%81%E7%AE%80%E4%BB%A3%E7%A0%81/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%