28个极简代码——python

1、大写首字母

s = 'hello world'
print(s.title())

输出:

Hello World

2、逗号连接

将列表连接成单个字符串,且每个元素间分隔方式设为逗号

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

输出:

My hobbies are:basketball,football,baseball

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

输出:

[[1, 2], [3, 4], [5]]

4、合并两个字典

def merge_dicts(a,b):
    c = a.copy()
    c.update(b)
    return c
a = {'x':1,'y':2}
b = {'z':3}
print(merge_dicts(a,b))
# python3.5以上,合并字典
print({**a,**b})

输出:

{'x': 1, 'y': 2, 'z': 3}
{'x': 1, 'y': 2, 'z': 3}

5、回文序列

检查给定的字符串是不是回文序列,首先把所有字母转化为小写,并移除非英文字母符号。最后,比较字符串与反字符串是否相等,相等则是回文序列

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

输出:

True

6、检查重复项

检查两列表是不是有重复项

def has_same(ls):
    return len(ls) != len(set(ls))
x = [1,2,3,4,3]
y = [1,2,3]
print(has_same(x))
print(has_same(y))

输出:

True
False

7、解包

将打包好的成对列表解开成两组不同的元组

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

输出:

[('a', 'c', 'e'), ('b', 'd', 'f')]

8、链式对比

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

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

输出:

True
False

9、链式函数调用

一行代码调用多个函数

def add(a,b):
    return a+b
def subtract(a,b):
    return a-b
a,b = 4,5
c,d = 5,6
print((subtract if a>b else add)(a,b))
print((subtract if c>d else add)(c,d))

输出:

9
11

10、列表的差

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

def unique(a,b):
    set_a = set(a)
    set_b = set(b)
    comparison = set_a.difference(set_b)
    return list(comparison)
print(unique([1,2,3],[1,2,4]))

输出:

[3]

11、内存占用

检查变量所占用内存

import sys
var = 25
print(sys.getsizeof(var))

输出:

28

12、使用枚举

除了使用for循环遍历,还可以使用枚举获取列表的值和索引

ls = ['a','b','c']
for index,value in enumerate(ls):
    print('Value:',value,'Index:',index)

输出:

Value: a Index: 0
Value: b Index: 1
Value: c Index: 2

13、首字母小写

def decapital(string):
    return string[:1].lower()+string[1:]
print(decapital('FooBar'))

输出:

fooBar

14、通过函数取差

首先应用一个指定的函数,然后返回应用函数后结果有差别的列表元素

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,4.5],floor))  #取整只有1.2不同
print(difference_by([{'x':2},{'x':1}],[{'x':1}],lambda v:v['x']))

输出:

[1.2]
[{'x': 2}]

15、不使用if-else的计算子

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

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

输出:

27

16、压缩

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

def compact(lst):
    return list(filter(bool,lst))
print(compact([0,1,False,2,'',3,'a','s',34]))

17、元素频率

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

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

输出:

2

18 、元音统计

用正则表达式,统计字符串中的元音(‘a’,‘e’,‘i’,‘o’,‘u’)的个数

import re
def count_yuan(str):
    return len(re.findall(r'[aeiou]',str,re.IGNORECASE))   #re返回一个列表,忽略大小写搜索
print(count_yuan('fadoor'))
print(count_yuan('YAeood'))

输出:

3
4

19、展开列表

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

def flatten(li):
    return sum(([x] if not isinstance(x,list) else flatten(x) for x in li),[])
print(flatten([1,[2],[[3,4],5]]))

输出:

[1, 2, 3, 4, 5]

20、重复元素判断

检测列表是否存在重复元素

def all_unique(ls):
    return len(ls) == len(set(ls))
x = [1,2,1,3,2,3,4,5]
y = [1,2,3,4]
print(all_unique(x))
print(all_unique(y))

输出:

False
True

21、字典默认值

通过key取对应的value值,可以通过以下方式设置默认值。如果get()方法没有设置默认值,如果遇到不存在的key,则返回None

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

输出:

1
None

22、字符元素组成

检查两字符串元素是否相同

from collections import Counter

def anagram(first,second):
    return Counter(first) == Counter(second)
print(anagram('abdc2','dab2c'))

输出:

True

23、字节占用

检测字符串所占字节数

def byte_size(s):
    return len(s.encode('utf-8'))
print(byte_size('Hello,world'))
print(byte_size('🆒'))

输出:

11
4

24、打印N次字符串

n = 2
s = 'csdn'
print(s*n)

输出:

csdncsdn

25、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
foo = [1,2,3]
print(shuffle(foo))

输出:

[3, 2, 1] #不是唯一值,是随机的

26、Try-else

使用try/except语句的时候可以加一个else子句,如果没有触发错误,运行这个子句

try:
    2*3
except TypeError:
    print('An exception was raised')
else:
    print('Thank god,no exception was raised')

输出:

Thank god,no exception was raised

27、执行时间

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

import time
start_time = time.time()
a = 1
b = 2
c = a * b
print(c)
end_time = time.time()
total_time = end_time - start_time
print('Time:',total_time)

输出:

2
Time: 0.0010042190551757812

28、两列表合并成字典

def to_dicts(keys,values):
    return dict(zip(keys,values))
keys = ['a','b','c']
values = [1,2,3]
print(to_dicts(keys,values))

输出:

{'a': 1, 'b': 2, 'c': 3}
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YYHhao.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值