Python是目前最流行的语言之一,它在数据科学、机器学习、web开发、脚本编写、自动化方面被许多人广泛使用。
因为python简单和易用性让他它如此的流行。
我将会介绍 10 个超简单的代码案例,你可以在 30 秒或更短的时间里理解和学习这些代码片段。
python资源群:1156465813
1.检查重复元素
下面的方法可以检查给定列表中是否有重复的元素。它使用了 set() 属性,该属性将会从列表中删除重复的元素。
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.首字母大写
以下代码段使用 title() 方法将字符串内的每个词进行首字母大写。
s = "programming is awesome"
print(s.title()) # Programming Is Awesome
4.间隔数
以下代码段可以用来转换一个二维数组。
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')]
5.计算所需时间
以下代码段可用于计算执行特定代码所需的时间。
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)
6.查找最常见元素
以下方法返回列表中出现的最常见元素。
def most_frequent(list):
return max(set(list), key = list.count)
list = [1,2,1,2,3,2,1,4,2]
most_frequent(list)
7.没有 if-else 语句的简单计算器
以下代码段将展示如何编写一个不使用 if-else 条件的简单计算器。
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25
8.列表扁平化
以下方法可使列表扁平化,类似于JavaScript中的[].concat(…arr)。
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]
9.元素顺序打乱
以下算法通过实现 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]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
10.使用枚举
以下方法将字典作为输入,然后仅返回该字典中的键。
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)