Python 核心编程
- [1. 数据类型](#1. 数据类型)
-
- [1.1 整型 int](#1.1 整型 int)
- [1.2 浮点数 float](#1.2 浮点数 float)
- [1.3 布尔类型 bool](#1.3 布尔类型 bool)
- [1.4 字符串 str](#1.4 字符串 str)
- [1.5 列表 list](#1.5 列表 list)
- [1.6 元组 tuple](#1.6 元组 tuple)
- [1.7 集合 set](#1.7 集合 set)
- [1.8 字典 dict](#1.8 字典 dict)
- [2. 逻辑结构、文件操作](#2. 逻辑结构、文件操作)
-
- [2.1 分支结构和三元表达](#2.1 分支结构和三元表达)
- [2.2 循环和遍历](#2.2 循环和遍历)
- [2.3 目录和路径](#2.3 目录和路径)
- [2.4 文件操作](#2.4 文件操作)
- [3. 函数、类、异常处理](#3. 函数、类、异常处理)
-
- [3.1 函数](#3.1 函数)
- [3.2 类](#3.2 类)
- [3.3 异常处理](#3.3 异常处理)
- [4. 包和模块、随机数](#4. 包和模块、随机数)
-
- [4.1 包和模块](#4.1 包和模块)
- [4.2 随机数](#4.2 随机数)
- [5. 生成器、高阶函数](#5. 生成器、高阶函数)
1. 数据类型
1.1 整型 int
- 没有长度限制
python
score = 95
python
type(score)
int
python
num = 888888888888888888888888888888888888888888888888888888888888888888888888888888
python
type(num)
int
python
num
888888888888888888888888888888888888888888888888888888888888888888888888888888
python
a = 4
b = 3
python
a + b
7
python
a - b
1
python
a * b
12
python
a / b
1.3333333333333333
python
a ** b
64
python
a ** (1 / b)
1.5874010519681994
python
import math
python
math.exp(3)
20.085536923187668
python
math.log(a)
1.3862943611198906
python
str(a)
'4'
python
c = int('5')
python
c
5
python
a > b
True
python
b > a
False
python
a == b
False
python
a >= b
True
python
a <= b
False
python
a != b
True
1.2 浮点数 float
- 浮点数是不精准存储
python
score = 82.11
python
type(score)
float
python
price = 5.55555555555555555555555555555555555555555555555555555555555
python
price
5.555555555555555
python
type(price)
float
python
distance = 1.5e-4
python
distance
0.00015
python
a = 1.5
b = 2.7
python
a + b
4.2
python
a - b
-1.2000000000000002
python
a * b
4.050000000000001
python
a / b
0.5555555555555555
python
import math
python
a = 3.5
python
a ** 2
12.25
python
a ** (1/2)
1.8708286933869707
python
a = 5.6
python
math.exp(a)
270.42640742615254
python
math.log(a)
1.7227665977411035
python
math.log2(a)
2.4854268271702415
python
str(a)
'5.6'
python
c = float('2.3132')
python
c
2.3132
python
a = 3.23452
python
math.ceil(a)
4
python
math.floor(a)
3
python
int(a)
3
python
round(a,2)
3.23
python
a = 1-0.55
python
a
0.44999999999999996
python
a = 3.5
b = 6.43
python
a < b
True
python
a = 1 - 0.55
python
a == 0.45
False
python
# 浮点数的相等不能直接比较
math.fabs(a - 0.45) < 1e-6
True
1.3 布尔类型 bool
- True 就是1 , False 就是0
python
True
True
python
False
False
python
result = True
python
3>2
True
python
1==2
False
python
True+1
2
python
2 ** True
2
python
1 / False
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[85], line 1
----> 1 1 / False
ZeroDivisionError: division by zero
python
True and True
True
python
True and False
False
python
True or False
True
python
not False
True
python
not True
False
1.4 字符串 str
- 单引号/双引号/三单引号/三双引号
python
s1 = '人工智能'
s2 = "人工智能"
python
type(s1),type(s2)
(str, str)
python
s3='''这是一个多行字符串
我可以自由换行
'''
python
s3
'这是一个多行字符串\n我可以自由换行\n'
python
s4="""三双引号
一样可以灵活换行"""
python
s4
'三双引号\n一样可以灵活换行'
python
len(s4)
13
python
s4.__len__()
13
python
s="qwertyuiopezxcfvgbnhmpdsfkpisjfoid"
python
s[0]
'q'
python
s[10]
'e'
python
s[-1]
'd'
python
s[-2]
'i'
python
s[:3]
'qwe'
python
s[3:5]
'rt'
python
s[1:-1]
'wertyuiopezxcfvgbnhmpdsfkpisjfoi'
python
len(s)
34
python
#[start:stop:step]
s[1:-4:3]
'wtiecghdks'
python
for ele in s[5:-6:4]:
print(ele)
y
p
c
b
p
k
python
s = " erwreqw"
python
s.strip()
'erwreqw'
python
s = " \t\n AI \t \n"
python
s
' \t\n AI \t \n'
python
s.strip()
'AI'
python
s = "人工 \t智能"
python
s.strip()
'人工 \t智能'
python
s.replace("\t","").replace(" ","")
'人工智能'
python
s = "1,2,3,4,5,6 "
python
ls = s.strip().split(",")
python
ls
['1', '2', '3', '4', '5', '6']
python
s = ",".join(ls)
python
s
'1,2,3,4,5,6'
python
s = "Hello World"
python
s.lower()
'hello world'
python
s.upper()
'HELLO WORLD'
python
s1 = "AI "
s2 = "人工智能 "
python
s1+s2
'AI 人工智能 '
python
s = 3*s1+ 5* s2
python
s
'AI AI AI 人工智能 人工智能 人工智能 人工智能 人工智能 '
python
s.count("AI")
3
python
'人工' in s
True
python
'智能' not in s
False
1.5 列表 list
- 元素有顺序,元素可以是任意类型,元素可以重复
python
ls = [1,2,3,4]
python
type(ls)
list
python
ls = list("abc")
python
ls
['a', 'b', 'c']
python
[1,2] == [2,1]
False
python
ls = [1,True,"asd",[1,2,3,4]]
python
ls
[1, True, 'asd', [1, 2, 3, 4]]
python
len(ls)
4
python
ls.__len__()
4
python
ls[0]
1
python
ls[:2]
[1, True]
python
ls[::2]
[1, 'asd']
python
ls[::-1]
[[1, 2, 3, 4], 'asd', True, 1]
python
for ele in ls:
print(ele)
1
True
asd
[1, 2, 3, 4]
python
ls=[]
python
len(ls)
0
python
ls.insert(0,"test")
python
ls
['test']
python
ls.insert(0,"1")
python
ls
['1', 'test']
python
ls.insert(100,"2")
python
ls
['1', 'test', '2']
python
ls.insert(-100,123)
python
ls
[123, '1', 'test', '2']
python
ls.append([1,2,3])
python
ls
[123, '1', 'test', '2', [1, 2, 3]]
python
ls.extend("mech")
python
ls
[123, '1', 'test', '2', [1, 2, 3], 'm', 'e', 'c', 'h']
python
ls.remove("1")
python
ls.remove([1,2,3])
python
ls
[123, 'test', '2', 'm', 'e', 'c', 'h']
python
ls.remove(321)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[217], line 1
----> 1 ls.remove(321)
ValueError: list.remove(x): x not in list
python
ls.pop()
'h'
python
ls
[123, 'test', '2', 'm', 'e', 'c']
python
ls.pop(10)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[220], line 1
----> 1 ls.pop(10)
IndexError: pop index out of range
python
ls.pop(-3)
'm'
python
ls
[123, 'test', '2', 'e', 'c']
python
ls[0] = 321
python
ls
[321, 'test', '2', 'e', 'c']
python
ls[-3:] = [1.1,2.2]
python
ls
[321, 'test', 1.1, 2.2]
python
ls.count(1)
0
python
321 in ls
True
1.6 元组 tuple
- 元素有顺序,可以是任意类型,不可修改
python
t1 = ()
python
type(t1)
tuple
python
t1
()
python
t2 = ("qwe")
python
t2
'qwe'
python
type(t2)
str
python
t3 = ("12",)
python
t3
('12',)
python
type(t3)
tuple
python
t4=(1,2,True,"ADSAS")
python
t4
(1, 2, True, 'ADSAS')
python
t5 = tuple("abd")
python
t5
('a', 'b', 'd')
python
t6=tuple([1,2,3,4,5,6])
python
t6
(1, 2, 3, 4, 5, 6)
python
# 元素不能修改
t6[3]=0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[248], line 2
1 # 元素不能修改
----> 2 t6[3]=0
TypeError: 'tuple' object does not support item assignment
python
t1 = tuple("abc")
python
t1
('a', 'b', 'c')
python
len(t1)
3
python
t1.__len__()
3
python
t1[0]
'a'
python
t1[-1]
'c'
python
t1[1::-1]
('b', 'a')
python
# 省略括号和结构赋值
t1 = (1,4.3)
python
t2 = 1,4.3
python
t1==t2
True
python
p1,p2 = t2
python
p1,p2
(1, 4.3)
python
p1
1
python
p2
4.3
python
p1,p2,p3 = t2
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[265], line 1
----> 1 p1,p2,p3 = t2
ValueError: not enough values to unpack (expected 3, got 2)
python
# 快速交换多个变量的值
A = 4
B = 5
python
A,B=B,A
python
A
5
python
B
4
python
ls = (1,2,3,True,1,3,4,2,12)
python
ls.count(1)
3
python
ls.count(True)
3
python
True in ls
True
python
False in ls
False
python
# tuple 元素不能修改吗?
t2 = (1,2,3)
python
t2[1]=3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[279], line 1
----> 1 t2[1]=3
TypeError: 'tuple' object does not support item assignment
python
t3=(1,2,[4,5,6])
python
# 列表是可变元素,值变了,但地址没变
t3[-1].append("ABD")
python
t3
(1, 2, [4, 5, 6, 'ABD'])
1.7 集合 set
- 元素的无序性/确定性/唯一性
python
s1 = {}
python
s1
{}
python
type(s1)
dict
python
t2 = set()
python
t2
set()
python
type(t2)
set
python
t3={1}
python
t3
{1}
python
t4={1,2,3,4,5,6,7}
python
t4
{1, 2, 3, 4, 5, 6, 7}
python
t5=set("abscs")
python
t5
{'a', 'b', 'c', 's'}
python
t6=set([1,2,3,4])
python
t6
{1, 2, 3, 4}
python
t7 = {1,1,1,1,2,3,4}
python
t7
{1, 2, 3, 4}
python
# 列表是可变的,不能作为集合的元素
t8 = {[1,2,3],True,"absd"}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[301], line 2
1 # 列表是可变的,不能作为集合的元素
----> 2 t8 = {[1,2,3],True,"absd"}
TypeError: unhashable type: 'list'
python
s = set("asdfdwsf")
python
len(s)
5
python
s.__len__()
5
python
s.add(True)
python
s
{True, 'a', 'd', 'f', 's', 'w'}
python
s.add('s')
python
s
{True, 'a', 'd', 'f', 's', 'w'}
python
s.remove('a')
python
s
{True, 'd', 'f', 's', 'w'}
python
s.remove('ffff')
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[313], line 1
----> 1 s.remove('ffff')
KeyError: 'ffff'
python
# 随机删除
s.pop()
'd'
python
s
{'s', 'w'}
python
a = {1,2,3,4,5,6,7}
b = {4,5,6,7,8,9}
python
a.intersection(b)
{4, 5, 6, 7}
python
b.intersection(a)
{4, 5, 6, 7}
python
a.union(b)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
python
b.union(a)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
python
1 in a
True
python
10 in b
False
1.8 字典 dict
- 元素成对出现,元素五顺序,key不可变,不重复,value无要求
python
d1 = {}
python
d1
{}
python
type(d1)
dict
python
len(d1)
0
python
d2 = {"name":"Tom"}
python
d2
{'name': 'Tom'}
python
d3 = {'name': 'Tom','age':12}
python
d3
{'name': 'Tom', 'age': 12}
python
len(d3)
2
python
# 可变类型不可以做key
# 可变类型: list/set/dict
# 不可变类型: int/float/bool/str/tuple*
d4 = {[1,2,3]:12}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[339], line 2
1 # 可变类型不可以做key
----> 2 d4 = {[1,2,3]:12}
TypeError: unhashable type: 'list'
python
d5 = dict(a=1,b=2,c=3)
python
d5
{'a': 1, 'b': 2, 'c': 3}
python
len(d5)
3
python
d5.__len__()
3
python
d6 = dict(name='Tom',age=22,school='北京大学')
python
d6
{'name': 'Tom', 'age': 22, 'school': '北京大学'}
python
d6["score"]=87
python
d6
{'name': 'Tom', 'age': 22, 'school': '北京大学', 'score': 87}
python
# 有则改之,无则追加
d2["score"] = 98
python
d2
{'name': 'Tom', 'score': 98}
python
d2["score"]
98
python
# 读取不存在的key会报错
d["asd"]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[364], line 2
1 # 读取不存在的key会报错
----> 2 d["asd"]
NameError: name 'd' is not defined
python
# 使用get读取更加安全
d6.get("abc",0)
0
python
d6
{'name': 'Tom', 'age': 22, 'school': '北京大学', 'score': 87}
python
d6.pop('name')
'Tom'
python
d6
{'age': 22, 'school': '北京大学', 'score': 87}
python
d.pop('age1')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[371], line 1
----> 1 d.pop('age1')
NameError: name 'd' is not defined
python
d6.keys()
dict_keys(['age', 'school', 'score'])
python
d6.values()
dict_values([22, '北京大学', 87])
python
d6.items()
dict_items([('age', 22), ('school', '北京大学'), ('score', 87)])
python
# 默认遍历key
for ele in d2:
print(ele)
name
score
python
# 遍历key
for key in d6.keys():
print(key)
age
school
score
python
# 遍历value
for value in d6.values():
print(value)
22
北京大学
87
python
# 遍历键值对
for key,value in d6.items():
print(key,value)
age 22
school 北京大学
score 87
python
'age' in d6
True
python
'age1' in d6
False
2. 逻辑结构、文件操作
2.1 分支结构和三元表达
python
if(1<2):
print("1<2")
1<2
python
age = 25
if age >= 18:
print("成年人")
else:
print("未成年")
成年人
python
score= 89
if score >=90:
print("优秀")
elif score >= 75:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
良好
python
# 三元表达
age = 3
True if age >= 18 else False
False
python
"成年人" if age >=18 else "未成年"
'未成年'
python
"成年人" if age >=18 else age
3
2.2 循环和遍历
python
num = 1
while True:
if num < 10:
num+=1
print(num)
else:
break
2
3
4
5
6
7
8
9
10
python
for _ in range(10):
print("Hello,Python!!!")
Hello,Python!!!
Hello,Python!!!
Hello,Python!!!
Hello,Python!!!
Hello,Python!!!
Hello,Python!!!
Hello,Python!!!
Hello,Python!!!
Hello,Python!!!
Hello,Python!!!
python
ls = [1,2,3,4,5,"Hello",False]
for ele in ls:
print(ele)
1
2
3
4
5
Hello
False
python
s = "asdfg"
for ele in s:
print(ele)
a
s
d
f
g
2.3 目录和路径
python
import os
python
# 路径是否存在(文件夹或文件)
os.path.exists(path="./abc")
True
python
# 路径拼接
os.path.join(".","abc","ddd")
'.\\abc\\ddd'
python
# 创建目录
save_path = "./abc/saved_weight"
# 如果不存在就创建
if not os.path.exists(path=save_path):
os.makedirs(save_path)
python
# 删除文件
if os.path.exists(path="ddd.ddd"):
os.remove()
python
# 删除目录
save_path = "./abc/saves_weights"
if os.path.exists(path=save_path):
print("存在")
os.removedirs(name=save_path)
python
# 遍历一个目录
root = "./"
for ele in os.listdir(root):
if os.path.isfile(ele):
print(ele,"文件")
elif os.path.isdir(ele):
print(ele,"目录")
.ipynb_checkpoints 目录
12.csv 文件
1234.txt 文件
abc 目录
P1_数据类型.ipynb 文件
P2_逻辑结构及文件操作.ipynb 文件
poem.txt 文件
saved_weight 目录
2.4 文件操作
python
# 打开、增删改查、关闭
python
f = open(file="./1234.txt",mode="r",encoding="utf8")
python
f.read()
'锄禾日当午\n汗滴禾下土'
python
f.read()
''
python
f.close()
python
# 更加优雅的写法
with open(file="./1234.txt",mode="r",encoding="utf8") as f:
while True:
line = f.readline().strip()
if line:
print(line)
else:
break
锄禾日当午
汗滴禾下土
python
# 写入:如果文件不存在则新建,如果存在则清空文件内容
with open(file="poem.txt",mode="w",encoding="utf8") as f:
f.write("举头望明月\n低头思故乡\n")
python
# 追加内容
with open(file="poem.txt",mode="a",encoding="utf8") as f:
f.write("举头望明月\n低头思故乡\n")
3. 函数、类、异常处理
3.1 函数
- 位置参数
- 默认参数
- 可变参数
- 匿名函数
python
# 定义参数
def fun():
pass
python
# 调用
fun()
python
callable(fun)
True
python
# 位置参数
def add(a,b):
return a+b
python
add(1,2)
3
python
# 默认参数
def area(r,pi=3.1415926):
return r*r*pi
python
area(r=3,pi=3.14)
28.26
python
# 可变参数
def add_num(*args):
s = 0
for ele in args:
s += ele
return s
python
add_num()
0
python
add_num(1)
1
python
add_num(1,2,3,4,5)
15
python
# 匿名函数
fn = lambda x: x ** 2
python
fn(3)
9
python
(lambda x,y:x+y)(1,2)
3
3.2 类
- 封装
- 继承
- 多态
python
class Car(object):
def __init__(self,color="Black",brand="BYD",price=50):
'''
自定属性
'''
self.color = color
self.brand = brand
self.price = price
def info(self):
'''
自定义方法
'''
print(self.color,self.brand,self.price)
def __repr__(self):
'''
重载父类的方法
'''
return 'Car'
python
car1 = Car(color="Blue")
python
car1
Car
python
print(car1.color)
Blue
python
car1.info()
Blue BYD 50
python
# 继承
car1.__repr__()
'Car'
python
o = object()
python
o.__repr__()
'<object object at 0x0000020EBEBE4ED0>'
python
# 多态
car1.__repr__()
'Car'
3.3 异常处理
- 异常基类 Exception
- 接收异常 try except else finally
- 抛出异常 raise
python
def divide(a, b):
return a / b
python
divide(1,2)
0.5
python
divide(2,0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[13], line 1
----> 1 divide(2,0)
Cell In[11], line 2, in divide(a, b)
1 def divide(a, b):
----> 2 return a / b
ZeroDivisionError: division by zero
python
"""
异常处理
- 守株待兔的操作
- 如果没有发生异常:不做任何额外处理
- 如果发生了异常,引导程序做出合理化的处理
"""
a = 3
b = 0
try:
result = divide(a,b)
print(result)
except Exception as e:
print(e)
else:
print("没有发生错误")
finally:
print("不管是否发生错误,我都会执行")
print("这里依然可以执行")
division by zero
不管是否发生错误,我都会执行
这里依然可以执行
python
# 抛出异常
a = 2
b = 3
def divide(a, b):
if isinstance(a, int) and isinstance(b, int) and b != 0:
return a / b
else:
raise Exception("参数错误")
python
divide(2,1)
2.0
python
divide(1,0.3)
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
Cell In[23], line 1
----> 1 divide(1,0.3)
Cell In[21], line 10, in divide(a, b)
8 return a / b
9 else:
---> 10 raise Exception("参数错误")
Exception: 参数错误
4. 包和模块、随机数
4.1 包和模块
- 包和模块是代码组织的一种方式,包就是一个文件夹,模块就是一个源码文件
- 避免重复造轮子,利用前人写好的包和模块
- 托管平台:pip 和 conda 管理工具
python
import numpy as np
python
np.__version__
'1.23.5'
python
np.e
2.718281828459045
python
import os
python
os.path.exists("./")
True
python
from matplotlib import pyplot as plt
- 定义自己的模块
- 在项目文件夹中新建一个文件夹名为 utils ,在里面新建一个 math.py文件,然后编辑函数
python
from utils import math
python
math.add(3,23)
26
python
math.sub(43,1)
42
4.2 随机数
- 概率论中随机试验产生的结果
- 数据科学中随机数很重要
python
import random
python
# 均匀分布
# 按照均匀分布生成一个随机数
random.uniform(0,100)
4.646385375119754
python
random.randint(0,100)
67
python
# 高斯分布
random.gauss(mu=0,sigma=1)
-2.9510713969400872
python
# 洗牌操作
x = [1,2,3,4,5,6,7,8,9,0]
print(x)
random.shuffle(x)
print(x)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[0, 6, 1, 4, 5, 7, 3, 9, 8, 2]
python
# 随机抽取
x = [1,2,3,4,5,6,7,8,9,0]
result = random.choice(x)
print(result)
9
python
ls = random.sample(x,3)
print(ls)
[5, 9, 3]
python
# 固定随机数,方便复现:种子固定了,随机规则就产生了,
random.seed(0)
x = [1,2,3,4,5,6,7,8,9,0]
result = random.sample(x,2)
print(result)
[7, 0]
5. 生成器、高阶函数
生成器
- 当数据集很大时,我们很难一次性将所有数据加载到内存中,而是按需加载,这时候就要用到生成器
- 模型训练时,数据经常会打包成生成器
- yield 和 return
- 列表生成器
- 打包数据集
python
# return 返回并跳出函数
def get_data():
ls = [0,1,2,3,4,5,6,7,8,9]
for ele in ls:
return ele
python
get_data()
0
python
# yield 构建生成器
def get_data():
ls = [0,1,2,3,4,5,6,7,8,9]
for ele in ls:
yield ele
python
gen = get_data()
python
for ele in gen:
print(ele)
0
1
2
3
4
5
6
7
8
9
python
ls = list(range(10))
python
ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
python
# 列表解析式 : for循环 + if判断
ls1 = [ele for ele in ls if ele % 2 == 1]
python
ls1
[1, 3, 5, 7, 9]
python
# 这样也可以构建生成器
gen1 = (ele for ele in ls if ele % 2 == 1)
python
for ele in gen1:
print (ele)
1
3
5
7
9
python
# 通过生成器来读取数据集
def get_dataset():
with open(file="dataset.csv",mode="r",encoding="utf8") as f:
line = f.readline()
while True:
line = f.readline()
if line:
yield line
else:
break
python
gen = get_dataset()
python
# 生成器是一次性的,从头读到尾之后,再想重新读就又要新的生成器了
next(gen)
'1.70,70,23,89\n'
python
for ele in gen:
print(ele)
1.67,71,23,79
1.75,72,22,84
1.74,73,23,86
1.79,74,21,56
高阶函数
- 把函数当做参数,自动化的实现底层遍历
- 数据科学中高阶函数很有用,可以极大提升效率
- map 映射
- reduce 聚合
- filter 过滤
- sorted 排序
- map
python
ls = [0,1,2,3,4,5,6,7,8,9]
def add(ele):
return ele + 0.5
python
ls1 = list(map(add,ls))
python
ls1
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
- reduce
python
from functools import reduce
python
sum(ls)
45
python
def add(a,b):
return a+b
python
reduce(add,ls)
45
python
reduce(lambda x, y: x * y, ls)
0
- filter
python
list(filter(lambda x : True if x % 2 == 0 else False, ls))
[0, 2, 4, 6, 8]
- sorted
python
sorted(ls, reverse = True)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
python
ls = [0,1,2,3,4,5,6,7,8,9]
python
ls.sort(reverse = True)
python
ls
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
python
ls2 = [(2,4),(1,6),(5,1),(3,8)]
python
sorted(ls2, key=lambda x:x[0], reverse=True)
[(5, 1), (3, 8), (2, 4), (1, 6)]
python
sorted(ls2, key=lambda x:x[1],reverse=False)
[(5, 1), (2, 4), (1, 6), (3, 8)]