有用的10个代码
、重复元素判定
以下方法可以检查给定列表是不是存在重复元素,它会使用 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、分块
给定具体的大小,定义一个函数以按照这个大小切割列表。
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]
3、压缩
这个方法可以将布尔型的值去掉,例如(False,None,0,“”),它使用 filter() 函数。
def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34])
#[ 1, 2, 3, 'a', 's', 34 ]
4、 使用枚举
我们常用 For 循环来遍历某个列表,同样我们也能枚举列表的索引与值。
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)\
5、解包
如下代码段可以将打包好的成对列表解开成两组不同的元组。
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed)
#[('a', 'c', 'e'), ('b', 'd', 'f')]
6、展开列表
该方法将通过递归的方式将列表的嵌套展开为单个列表。
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]
7、 列表的差
该方法将返回第一个列表的元素,其不在第二个列表内。如果同时要反馈第二个列表独有的元素,还需要加一句 set_b.difference(set_a)。
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]
8、 执行时间
如下代码块可以用来计算执行特定代码所花费的时间。
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)
9、 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]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
10、 交换值
不需要额外的操作就能交换两个变量的值。
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]
好玩的两个代码:
画一个玫瑰花:
import turtle
# 设置初始位置
turtle.penup() # 提起画笔
turtle.left(90) # 逆时针旋转九十度
turtle.fd(200) # 向前移动一段距离 fd=forward
turtle.pendown() # 放下画笔移动画笔开始绘制
turtle.right(90) # 顺时针旋转九十度
# 花蕊
turtle.fillcolor("red") # 填充颜色
turtle.begin_fill() # 开始填充
turtle.circle(10, 180) # 画一圆,10是半径,180是弧度
turtle.circle(25, 110)
turtle.left(50)
turtle.circle(60, 45)
turtle.circle(20, 170)
turtle.right(24)
turtle.fd(30)
turtle.left(10)
turtle.circle(30, 110)
turtle.fd(20)
turtle.left(40)
turtle.circle(90, 70)
turtle.circle(30, 150)
turtle.right(30)
turtle.fd(15)
turtle.circle(80, 90)
turtle.left(15)
turtle.fd(45)
turtle.right(165)
turtle.fd(20)
turtle.left(155)
turtle.circle(150, 80)
turtle.left(50)
turtle.circle(150, 90)
turtle.end_fill() # 结束填充
# 花瓣1
turtle.left(150)
turtle.circle(-90, 70)
turtle.left(20)
turtle.circle(75, 105)
turtle.setheading(60) # urtle.setheading(angle) 或 turtle.seth(angle):改变行进方向 angle:行进方向的绝对角度,可以为负值
turtle.circle(80, 98)
turtle.circle(-90, 40)
# 花瓣2
turtle.left(180)
turtle.circle(90, 40)
turtle.circle(-80, 98)
turtle.setheading(-83)
# 叶子1
turtle.fd(30)
turtle.left(90)
turtle.fd(25)
turtle.left(45)
turtle.fillcolor("green")
turtle.begin_fill()
turtle.circle(-80, 90)
turtle.right(90)
turtle.circle(-80, 90)
turtle.end_fill()
turtle.right(135)
turtle.fd(60)
turtle.left(180)
turtle.fd(85)
turtle.left(90)
turtle.fd(80)
# 叶子2
turtle.right(90)
turtle.right(45)
turtle.fillcolor("green")
turtle.begin_fill()
turtle.circle(80, 90)
turtle.left(90)
turtle.circle(80, 90)
turtle.end_fill()
turtle.left(135)
turtle.fd(60)
turtle.left(180)
turtle.fd(60)
turtle.right(90)
turtle.circle(200, 60)
# 设置成画完不会自动退出
turtle.done()
最后打印一个爱心
# 打印爱心图案
def print_love():
myData = "love"
for char in myData.split():
allChar = []
for y in range(12, -12, -1):
lst = []
lst_con = ''
for x in range(-30, 30):
formula = ((x * 0.05) ** 2 + (y * 0.1) ** 2 - 1) ** 3 - (x * 0.05) ** 2 * (y * 0.1) ** 3
if formula <= 0:
lst_con += char[(x) % len(char)]
else:
lst_con += ' '
lst.append(lst_con)
allChar += lst
print('\n'.join(allChar))
time.sleep(1)
if __name__ == '__main__':
print_love()