简单分享20段非常简单的python代码,通过他们我们可以实现一些非常简单的功能。


日常非常常用的功能。
python 20段简单实用的代码

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.内存占用的判断
import sys
variable = 30
print(sys.getsizeof(variable)) # 24

3.字节占用的判断
def byte_size(string):
return(len(string.encode('utf-8')))
byte_size(' ') # 4
byte_size('Hello World') # 11

4.输出n次字符串
n = 2;
s ="Programming";
print(s * n);#ProgrammingProgramming

5.大写第一个字母
s = "programming is awesome"
print(s.title())

6.去除选定内容
def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34])#[ 1, 2, 3, 'a', 's', 34 ]

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

8.小写第一个字母
def decapitalize(string):
return str[:1].lower() + str[1:]
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar') # 'fooBar'

9.将嵌套列表展开
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]

10.合并字典
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}

11.列表转化为字典
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}

12.枚举
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)

13.设置代码执行的时间
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)

14.元素频率
def most_frequent(list):
return max(set(list), key = list.count)
list = [1,2,1,2,3,2,1,4,2]
most_frequent(list)

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

16.不通过ifelse进行计算
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action'-') # 25

17.展开列表
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]

18.交换值
def swap(a, b):
return b, a
a, b = -1, 14
swap(a, b) # (14, -1)
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

19.字典默认值
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3

20.合并字典
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}
今天的内容简单说到这里,有关python的问题,欢迎评论留言。

本文作者:博主:     文章标题:python 20段简单实用的代码
本文地址:https://zjzdmc.top/jsfx/134.html     
版权说明:若无注明,本文皆为“Datehoer的Blog-个人博客-技术分享”原创,转载请保留文章出处。
最后修改:2021 年 04 月 19 日 02 : 39 PM
如果觉得我的文章对你有用,请随意赞赏