即学即用的 30 段 Python 非常实用的代码
真爱,请置顶或星标
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
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
import sys
variable = 30
print(sys.getsizeof(variable)) # 24
def byte_size(string):
return(len(string.encode( utf-8 )))
byte_size( ???? ) # 4
byte_size( Hello World ) # 11
n = 2;
s ="Programming"; print(s * n);
# ProgrammingProgramming
s = "programming is awesome"
print(s.title()) # Programming Is Awesome
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]
def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, , 3, a , s , 34]) # [ 1, 2, 3, a , s , 34 ]
array = [[ a , b ], [ c , d ], [ e , f ]]
transposed = zip(*array)
print(transposed) # [( a , c , e ), ( b , d , f )]
a = 3
print( 2 < a < 8) # True
print(1 == a < 2) # False
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming
import re
def count_vowels(str):
return len(len(re.findall(r [aeiou] , str, re.IGNORECASE)))
count_vowels( foobar ) # 3
count_vowels( gym ) # 0
def decapitalize(string):
return str[:1].lower() + str[1:]
decapitalize( FooBar ) # fooBar
decapitalize( FooBar ) # fooBar
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
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
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]
def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ x : 2 }, { x : 1 }], [{ x : 1 }], lambda v : v[ x ]) # [ { x: 2 } ]
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
def has_duplicates(lst):
return len(lst) != len(set(lst))
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False
def merge_two_dicts(a, b):
c = a.copy() # make a copy of a
c.update(b) # modify keys and values of a with the ones from b
return c
a = { x : 1, y : 2}
b = { y : 3, z : 4}
print(merge_two_dicts(a, b)) # { y : 3, x : 1, 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)) # { y : 3, x : 1, z : 4}
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, c : 4, b : 3}
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)
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: , 1.1205673217773438e-05)
try:
2*3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")
#Thank God, no exceptions were raised.
def most_frequent(list):
return max(set(list), key = list.count)
list = [1,2,1,2,3,2,1,4,2]
most_frequent(list)
def palindrome(string):
from re import sub
s = sub( [W_] , , string.lower())
return s == s[::-1]
palindrome( taco cat ) # True
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action[ - ](50, 25)) # 25
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]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
def swap(a, b):
return b, a
a, b = -1, 14
swap(a, b) # (14, -1)
d = { a : 1, b : 2}
print(d.get( c , 3)) # 3
喜欢文章,点个在看
即学即用的 30 段 Python 非常实用的代码相关推荐
- 即学即用的30段Python实用代码
(图片付费下载自视觉中国) 原标题 | 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less 作 者 | Fatos ...
- python基础30个常用代码-即学即用的 30 段 Python 实用代码
Python是目前最流行的语言之一,它在数据科学.机器学习.web开发.脚本编写.自动化方面被许多人广泛使用.它的简单和易用性造就了它如此流行的原因. 在本文中,我们将会介绍 30 个简短的代码片段, ...
- 简单python脚本实例-超实用的 30 段 Python 案例
Python是目前最流行的语言之一,它在数据科学.机器学习.web开发.脚本编写.自动化方面被许多人广泛使用. 它的简单和易用性造就了它如此流行的原因. 如果你正在阅读本文,那么你或多或少已经使用过P ...
- 30个Python常用极简代码,拿走就用
点击上方"视学算法",选择加"星标"或"置顶" 重磅干货,第一时间送达 作者丨Fatos Morina 来源丨Python 技术 编辑丨极市 ...
- python1000个常用代码-30个Python常用极简代码,拿走就用
学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则.本文是 30 个极简任务,初学者可以尝试着自己实现:本文同样也是 30 段代码,Python 开发者也可以看看是不是 ...
- 零基础python必背代码-30个Python常用极简代码,拿走就用
学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则.本文是 30 个极简任务,初学者可以尝试着自己实现:本文同样也是 30 段代码,Python 开发者也可以看看是不是 ...
- 30个Python常用极简代码
学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则.本文是 30 个极简任务,初学者可以尝试着自己实现:本文同样也是 30 段代码,Python 开发者也可以看看是不是 ...
- 30个Python常用极简代码,拿走就用,赶紧收藏!
学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则.本文是 30 个极简任务,初学者可以尝试着自己实现:本文同样也是 30 段代码,Python 开发者也可以看看是不是 ...
- python基础30个常用代码-30个Python常用极简代码,拿走就用
学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则.本文是 30 个极简任务,初学者可以尝试着自己实现:本文同样也是 30 段代码,Python 开发者也可以看看是不是 ...
最新文章
- 解决问题:chmod: changing permissions of ‘...‘: Read-only file system和/dev/sda1 is write-protected but ex
- 打印 指定目录下和子目录下的的所有.java文件的路径. (使用FileFilter过滤器)
- notion函数_Notion使用指南 | Database篇
- lamp中php怎么连接mysql_LAMP分离安装环境下,php无法连接mysql的问题
- EasyExcel简单使用
- mac php5.6 gd 扩展,mac 编译安装php5.6.40
- 经典小游戏开发思路和算法之拼图(1)
- 批量插入图片到Excel中批注中,Excel插件 E灵
- Java 获取屏幕尺寸
- 生活随记 - 拥抱变化
- E4A第一期-E4A的简单用法
- 欧几里得变换(Euclidean transformation)详解
- 路由器选华硕还是tp_华硕路由器设置
- Cadence OrCAD Capture CIS 输出带属性的PDF原理图
- 计算时间复杂度--(简单版)
- centos关闭自动锁屏
- python基础复习(30)--string[start:end:step] start默认0 end默认列尾 step默认1
- [leetcode] 质因数分解
- 基于51单片机的废气检测I2Cproteus仿真
- 数理方程与特殊函数|三类稳定问题
热门文章
- 【Codeforces】401C Team (01010110...)
- 怎么控制table的大小java_如何查询Table占用空间的大小
- 详解 Python 如何将爬取到的数据分别存储到 txt、excel、mysql 中!
- 技术驰援抗疫一线, Python 线上峰会免费学!
- 2019年,自动化机器学习AutoML技术还火吗? | BDTC 2019
- Reddit票选 | 2019年绝对不能错过的机器学习论文
- AI算法在FPGA芯片上还有这种操作?| 技术头条
- 面试大法——算法、Python、机器学习等笔试面经资源|干货收藏
- 资源 | 李飞飞、吴恩达、Bengio等人的15大顶级深度学习课程,你收集全了吗?
- 漫画 | 你对加班有什么看法?