首页 > 编程知识 正文

python常用函数学习笔记(python中常用的函数)

时间:2023-12-22 19:14:06 阅读:319154 作者:HUDB

本文目录一览:

Python常用函数三有哪些?这7个函数使用频率最高,总算搞明白了

1.1 例如:print(hex(2))案例

1.2 输出函数:print(hex(2))

1.3 输出结果:0x2

1.4 解析说明:返回16进制的数。

2.1 例如:print(chr(10))案例

2.2 输出函数:print(chr(10))

2.3 输出结果:0o12

2.4 解析说明:返回当前整数对应的ASCll码

3.1 例如:print(ord("b"))案例

3.2 输出函数:print(ord("b"))

3.3 输出结果:98

3.4 解析说明:返回当前ASCll码的10进制数

4.1 例如:print(chr(97))

4.2 输出函数:print(chr(97))

4.3 输出结果:b

4.4 解析说明:返回当前ASCll码的10进制数。

案例一:给你一个字符串,s = 'hello kitty'

1.1 输出函数:print(s.capitalize())

1.2 输出结果:0x2

1.3 解析说明:返回16进制的数。

2.1输出函数:print(s.replace('kitty','kuang'))

2.2 输出结果:hello kuang

2.3 解析说明:替换功能,将kitty换成kuang。

2.4 输出函数:print(s.replace('4','KK'))

2.5 输出结果:12KK12KK

2.6 解析说明:所有的4都替换成KK

2.7 输出函数:print(s.replace('4','KK'))

2.8 输出结果:12KK12KK124

2.9 解析说明:将前两个的4替换成go

案例一:给你一个字符串,ip = '192.168.1.1'

3.1 输出函数:print(ip.split(','))

3.2 输出结果:['192.168.1.1']

3.3 解析说明:将字符串分割成列表

案例一:给你一个字符串,ip = '192.168.1.1'

3.3 输出函数:print(ip.split(',',2))

3.4 输出结果:['192.168.1.1']

3.5 解析说明:从第二个开始分割成列表

Python基础 numpy中的常见函数有哪些

有些Python小白对numpy中的常见函数不太了解,今天小编就整理出来分享给大家。

Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy、matplotlib一起使用。其实,list已经提供了类似于矩阵的表示形式,不过numpy为我们提供了更多的函数。

数组常用函数

1.where()按条件返回数组的索引值

2.take(a,index)从数组a中按照索引index取值

3.linspace(a,b,N)返回一个在(a,b)范围内均匀分布的数组,元素个数为N个

4.a.fill()将数组的所有元素以指定的值填充

5.diff(a)返回数组a相邻元素的差值构成的数组

6.sign(a)返回数组a的每个元素的正负符号

7.piecewise(a,[condlist],[funclist])数组a根据布尔型条件condlist返回对应元素结果

8.a.argmax(),a.argmin()返回a最大、最小元素的索引

改变数组维度

a.ravel(),a.flatten():将数组a展平成一维数组

a.shape=(m,n),a.reshape(m,n):将数组a转换成m*n维数组

a.transpose,a.T转置数组a

数组组合

1.hstack((a,b)),concatenate((a,b),axis=1)将数组a,b沿水平方向组合

2.vstack((a,b)),concatenate((a,b),axis=0)将数组a,b沿竖直方向组合

3.row_stack((a,b))将数组a,b按行方向组合

4.column_stack((a,b))将数组a,b按列方向组合

数组分割

1.split(a,n,axis=0),vsplit(a,n)将数组a沿垂直方向分割成n个数组

2.split(a,n,axis=1),hsplit(a,n)将数组a沿水平方向分割成n个数组

数组修剪和压缩

1.a.clip(m,n)设置数组a的范围为(m,n),数组中大于n的元素设定为n,小于m的元素设定为m

2.a.compress()返回根据给定条件筛选后的数组

数组属性

1.a.dtype数组a的数据类型

2.a.shape数组a的维度

3.a.ndim数组a的维数

4.a.size数组a所含元素的总个数

5.a.itemsize数组a的元素在内存中所占的字节数

6.a.nbytes整个数组a所占的内存空间7.a.astype(int)转换a数组的类型为int型

数组计算

1.average(a,weights=v)对数组a以权重v进行加权平均

2.mean(a),max(a),min(a),middle(a),var(a),std(a)数组a的均值、最大值、最小值、中位数、方差、标准差

3.a.prod()数组a的所有元素的乘积

4.a.cumprod()数组a的元素的累积乘积

5.cov(a,b),corrcoef(a,b)数组a和b的协方差、相关系数

6.a.diagonal()查看矩阵a对角线上的元素7.a.trace()计算矩阵a的迹,即对角线元素之和

以上就是numpy中的常见函数。更多Python学习推荐:PyThon学习网教学中心。

python 十条函数

def age():

    """This funcation aske user's age and return a interge

    n=int(input('Please input your age:'))

    return n

...

就这样写好了,没时间玩这么简单的东西。

pytorch 常用函数参数详解

1、torch.cat(inputs, dim=0) - Tensor 

参考链接:

[Pytorch] 详解 torch.cat()

Pytorch学习笔记(一):torch.cat()模块的详解

函数作用:cat 是 concatnate 的意思:拼接,联系在一起。在给定维度上对输入的 Tensor 序列进行拼接操作。torch.cat 可以看作是 torch.split 和 torch.chunk 的反操作

参数:

inputs(sequence of Tensors):可以是任意相同类型的 Tensor 的 python 序列

dim(int, optional):defaults=0

dim=0: 按列进行拼接 

dim=1: 按行进行拼接

dim=-1: 如果行和列数都相同则按行进行拼接,否则按照行数或列数相等的维度进行拼接

假设 a 和 b 都是 Tensor,且 a 的维度为 [2, 3],b 的维度为 [2, 4],则

torch.cat((a, b), dim=1) 的维度为 [2, 7]

2、torch.nn.CrossEntropyLoss()

函数作用:CrossEntropy 是交叉熵的意思,故而 CrossEntropyLoss 的作用是计算交叉熵。CrossEntropyLoss 函数是将 torch.nn.Softmax 和 torch.nn.NLLLoss 两个函数组合在一起使用,故而传入的预测值不需要先进行 torch.nnSoftmax 操作。

参数:

input(N, C):N 是 batch_size,C 则是类别数,即在定义模型输出时,输出节点个数要定义为 [N, C]。其中特别注意的是 target 的数据类型需要是浮点数,即 float32

target(N):N 是 batch_size,故 target 需要是 1D 张量。其中特别注意的是 target 的数据类型需要是 long,即 int64

例子:

loss = nn.CrossEntropyLoss()

input = torch.randn(3, 5, requires_grad=True, dtype=torch.float32)

target = torch.empty(3, dtype=torch.long).random_(5)

output = loss(input, target)

output

输出为:

tensor(1.6916, grad_fn=NllLossBackward)

68 个 Python 内置函数详解

内置函数就是Python给你提供的,拿来直接用的函数,比如print.,input等。

截止到python版本3.6.2 ,python一共提供了68个内置函数,具体如下

本文将这68个内置函数综合整理为12大类,正在学习Python基础的读者一定不要错过,建议收藏学习!

(1)列表和元组

(2)相关内置函数

(3)字符串

frozenset 创建一个冻结的集合,冻结的集合不能进行添加和删除操作。

语法:sorted(Iterable, key=函数(排序规则), reverse=False)

语法:fiter(function. Iterable)

function: 用来筛选的函数. 在filter中会自动的把iterable中的元素传递给function. 然后根据function返回的True或者False来判断是否保留留此项数据 , Iterable: 可迭代对象

搜索公众号顶级架构师后台回复“面试”,送你一份惊喜礼包。

语法 : map(function, iterable)

可以对可迭代对象中的每一个元素进行映射. 分别去执行 function

hash : 获取到对象的哈希值(int, str, bool, tuple). hash算法:(1) 目的是唯一性 (2) dict 查找效率非常高, hash表.用空间换的时间 比较耗费内存

python3.4学习笔记 3.x和2.x的区别,持续更新

python3.4学习笔记(四) 3.x和2.x的区别

在2.x中:print html,3.x中必须改成:print(html)

import urllib2

ImportError: No module named 'urllib2'

在python3.x里面,用urllib.request代替urllib2

import thread

ImportError: No module named 'thread'

在python3.x里面,用_thread(在前面加一个下划线)代替thread

在2.x中except Exception,e : 3.x中改为except (Exception):

=================================

print函数

虽然print语法是Python 3中一个很小的改动,且应该已经广为人知,但依然值得提一下:Python 2中的print语句被Python 3中的print()函数取代,这意味着在Python 3中必须用括号将需要输出的对象括起来。

在Python 2中使用额外的括号也是可以的。但反过来在Python 3中想以Python2的形式不带括号调用print函数时,会触发SyntaxError。

Python 2.7.6

print 'Python', python_version()

print 'Hello, World!'

print('Hello, World!')

print "text", ; print 'print more text on the same line'

输出:

Hello, World!

Hello, World!

text print more text on the same line

---------------------------

Python 3.4.1

print('Python', python_version())

print('Hello, World!')

print("some text,", end="")

print(' print more text on the same line')

输出:

Hello, World!

some text, print more text on the same line

print 'Hello, World!'

File "ipython-input-3-139a7c5835bd", line 1

print 'Hello, World!'

^

SyntaxError: invalid syntax

注意:在Python中,带不带括号输出”Hello World”都很正常。

但如果在圆括号中同时输出多个对象时,就会创建一个元组,这是因为在Python 2中,print是一个语句,而不是函数调用。

print 'Python', python_version()

print('a', 'b')

print 'a', 'b'

Python 2.7.7

('a', 'b')

a b

---------------------------------

整数除法

由于人们常常会忽视Python 3在整数除法上的改动(写错了也不会触发Syntax Error),所以在移植代码或在Python 2中执行Python 3的代码时,需要特别注意这个改动。

所以,我还是会在Python 3的脚本中尝试用float(3)/2或 3/2.0代替3/2,以此来避免代码在Python

2环境下可能导致的错误(或与之相反,在Python 2脚本中用from __future__ import division来使用Python

3的除法)。

Python 2.7.6

3 / 2 = 1

3 // 2 = 1

3 / 2.0 = 1.5

3 // 2.0 = 1.0

Python 3.4.1

3 / 2 = 1.5

3 // 2 = 1

3 / 2.0 = 1.5

3 // 2.0 = 1.0

---------------------------------

Unicode

Python 2有基于ASCII的str()类型,其可通过单独的unicode()函数转成unicode类型,但没有byte类型。

而在Python 3中,终于有了Unicode(utf-8)字符串,以及两个字节类:bytes和bytearrays。

Python 2.7.6

print type(unicode('this is like a python3 str type'))

type 'unicode'

print type(b'byte type does not exist')

type 'str'

print 'they are really' + b' the same'

they are really the same

print type(bytearray(b'bytearray oddly does exist though'))

type 'bytearray'

Python 3.4.1 has class 'bytes'

print('and Python', python_version(), end="")

print(' also has', type(bytearray(b'bytearrays')))

and Python 3.4.1 also has class 'bytearray'

1

'note that we cannot add a string' + b'bytes for data'

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

ipython-input-13-d3e8942ccf81 in module()

---- 1 'note that we cannot add a string' + b'bytes for data'

TypeError: Can't convert 'bytes' object to str implicitly

=================================

python 2.4 与 python 3.0 的比较

一、 print 从语句变为函数

原: print 1,2+3

改为: print ( 1,2+3 )

二、range 与 xrange

原 : range( 0, 4 ) 结果 是 列表 [0,1,2,3 ]

改为:list( range(0,4) )

原 : xrange( 0, 4 ) 适用于 for 循环的变量控制

改为:range(0,4)

三、字符串

原: 字符串以 8-bit 字符串存储

改为: 字符串以 16-bit Unicode 字符串存储

四、try except 语句的变化

在2.x中except Exception,e : 3.x中改为except (Exception):

五、打开文件

原: file( ..... )

或 open(.....)

改为:

只能用 open(.....)

六、从键盘录入一个字符串

原: raw_input( "提示信息" )

改为: input( "提示信息" )

七、bytes 数据类型

A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 = x 256.

bytes 可以看成是“字节数组”对象,每个元素是 8-bit 的字节,取值范围 0~255。

由于在 python 3.0中字符串以 unicode 编码存储,当写入二进制文件时,字符串无法直接写入(或读取),必须以某种方式的编码为字节序列后,方可写入。

(一)字符串编码(encode) 为 bytes

例: s = "张三abc12"

b = s.encode( 编码方式)

# b 就是 bytes 类型的数据

# 常用的编码方式为 : "uft-16" , "utf-8", "gbk", "gb2312", "ascii" , "latin1" 等

# 注 : 当字符串不能编码为指定的“编码方式”时,会引发异常

(二) bytes 解码(decode)为字符串

s = "张三abc12"

b = s.encode( "gbk") # 字符串 s 编码为 gbk 格式的字节序列

s1 = b.decode("gbk") # 将字节序列 b以gbk格式 解码为字符串

# 说明,当字节序列不能以指定的编码格式解码时会引发异常

(三)使用方法举例

#coding=gbk

f = open("c:\1234.txt", "wb")

s = "张三李四abcd1234"

# -------------------------------

# 在 python2.4 中我们可以这样写:

# f.write( s )

# 但在 python 3.0中会引发异常

# -------------------------------

b = s.encode("gbk")

f.write( b )

f.close()

input("?")

读取该文件的例子:

#coding=gbk

f = open("c:\1234.txt", "rb")

f.seek(0,2) #定位至文件尾

n = f.tell() #读取文件的字节数

f.seek(0,0) #重新定位至文件开始处

b = f.read( n )

# ------------------------------

# 在 python 2.4 中 b 是字符串类型

# 要 python 3.0 中 b 是 bytes 类型

# 因此需要按指定的编码方式确码

# ------------------------------

s = b.decode("gbk")

print ( s )

# ------------------------------

# 在 python 2.4 中 可以写作 print s 或 print ( s )

# 要 python 3.0 中 必须写作 print ( s )

# ------------------------------

f.close()

input("?")

运行后应显示:

张三李四abcd1234

(四) bytes序列,一但形成,其内容是不可变的,例:

s="ABCD"

b=s.encode("gbk")

print b[0] # 显示 65

b[0] = 66

# 执行该句,出现异常: 'bytes' object does not support item assignment

八、 chr( K ) 与 ord( c )

python 2.4.2以前

chr( K ) 将编码K 转为字符,K的范围是 0 ~ 255

ord( c ) 取单个字符的编码, 返回值的范围: 0 ~ 255

python 3.0

chr( K ) 将编码K 转为字符,K的范围是 0 ~ 65535

ord( c ) 取单个字符的编码, 返回值的范围: 0 ~ 65535

九、 除法运算符

python 2.4.2以前

10/3 结果为 3

python 3.0

10 / 3 结果为 3.3333333333333335

10 // 3 结果为 3

十、字节数组对象 --- 新增

(一) 初始化

a = bytearray( 10 )

# a 是一个由十个字节组成的数组,其每个元素是一个字节,类型借用 int

# 此时,每个元素初始值为 0

(二) 字节数组 是可变的

a = bytearray( 10 )

a[0] = 25

# 可以用赋值语句更改其元素,但所赋的值必须在 0 ~ 255 之间

(三) 字节数组的切片仍是字节数组

(四) 字符串转化为字节数组

#coding=gbk

s ="你好"

b = s.encode( "gbk") # 先将字符串按某种“GBK”编码方式转化为 bytes

c = bytearray( b ) #再将 bytes 转化为 字节数组

也可以写作

c = bytearray( "你好", "gbk")

(五) 字节数组转化为字符串

c = bytearray( 4 )

c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68

s = c.decode( "gbk" )

print ( s )

# 应显示: ABCD

(六) 字节数组可用于写入文本文件

#coding=gbk

f = open("c:\1234.txt", "wb")

s = "张三李四abcd1234"

# -------------------------------

# 在 python2.4 中我们可以这样写:

# f.write( s )

# 但在 python 3.0中会引发异常

# -------------------------------

b = s.encode("gbk")

f.write( b )

c=bytearray( "王五","gbk")

f.write( c )

f.close()

input("?")

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。