zoukankan      html  css  js  c++  java
  • 【Python学习笔记】之基础语法和函数

    一、基础语法和函数相关

    1.1 len()函数

    返回对象(字符、列表、元祖等)的长度或项目个数。

    >>>str = "runoob"
    >>> len(str)             # 字符串长度
    6
    >>> l = [1,2,3,4,5]
    >>> len(l)               # 列表元素个数
    5
    

    1.2 chr()函数

    用于将一个范围在range(256)内的整数(也即是 0~255)转换成对应的ASCII码字符。

    >>> print chr(0x30)    # 十六进制
    0
    >>> print chr(1)    # 十进制数,ASCII码1表示start of heading,什么也不输出
    
    >>> chr(1)
    '\x01'
    

    与此相对应的有一个函数 ord(),则是返回单个ASCII字符对应的ASCII值或Unicode值。

    >>> ord('d')
    100
    >>> ord('A')
    65
    

    1.3 xrange() 函数

    xrange()函数用法与range()完全相同,所不同的是 xrange() 生成的不是一个数组,而是一个生成器。使用方法如下:

    1 xrange(stop)
    2 xrange(start, stop[, step])
    

    参数说明:

    • start: 计数从 start 开始。默认为0。如xrange(5)等价于xrange(0, 5)
    • stop: 计数到 stop 结束,但不包括 stop。如xrange(0, 5)[0, 1, 2, 3, 4]没有5。
    • step: 步长,默认为1。如xrange(0, 5)等价于xrange(0, 5, 1)

    range() 方法返回的是一个list对象,它需要开辟专门的空间保存序列中所有的元素。
    xrange() 方法返回的是xrange对象,它是一个序列对象,但并不保存序列中的元素。

    根据python官方文档的定义,一个序列对象不必要保存所有的元素。
    如果只对序列进行读操作,xrange()方法效率较高;但如果要改变序列的元素,或者需要对序列增删元素,那么只能通过range()方法生成一个list对象。

    1.4 with关键字

    如果你有两个想做的操作,你想要这两个操作成对执行,中间插入一段其他的代码,那么使用 with 就是一种很方便的方法。
    最经典的例子就是打开一个文件,对文件进行操作然后关闭文件。

    1 with open('output.txt', 'w') as f:
    2     f.write('Hi there!')
    

    上面的with语句会在嵌入的程序运行完后自动关闭文件。好处就是无论嵌套模块如何退出,都可以保证文件被关闭。

    如果嵌套模块结束之前有异常发生,系统将在异常被外部异常处理程序捕获之前关闭该文件。
    如果嵌套模块中包含有return语句、continue语句或者break语句,with语句一样可以在跳转之前自动关闭文件。

    1.5 lambda表达式

    相对于def定义的函数而言,lambda表达式则简单很多,因为其主体是一个表达式而非代码块,
    并允许在代码内嵌入一个函数定义,不过一般只能封装有限的逻辑。

    如下面的例子所示,lambda表达式定义了一个匿名函数,用于筛选100以内3的倍数,并生成一个列表。

    list (filter(lambda x:True if x % 3 == 0 else False, range(100)))
    

    当然lambda表达式也可以嵌套在函数体内,使用的时候可以用一个变量来接收,如下:

    def make_repeat(n):
        return lambda s : s * n
    
    double = make_repeat(2) 	# double变量此处是一个函数
    print (double(8))    		# 使用double向lambda表达式里的s传一个参数,并得到表达式的结果
    

    1.6 内置函数round()

    round(number, digits)
    
    • number 给定输入值,即待求解的值。
    • digits 指定小数位数,默认为0,此时返回的是int型整数。也就是保留几位小数前提下的四舍五入。

    该函数根据指定的小数位数对给定输入值进行四舍五入并返回结果。返回值是float类型。

    print(round(3.14159))
    print(round(3.14159,0))
    print(round(3.14159,1))
    print(round(3.14159,2))
    print(round(-3.14159))
    print(round(-3.14159,0))
    print(round(-3.14159,1))
    print(round(-3.14159,2))
    
    3			#round(3.14159)
    3.0			#round(3.14159,0)
    3.1			#round(3.14159,1)
    3.14			#round(3.14159,2)
    -3			#round(-3.14159)
    -3.0			#round(-3.14159,0)
    -3.1			#round(-3.14159,1)
    -3.14			#round(-3.14159,2)
    

    值得注意的是python内置函数round()采用的银行家舍入法(Banker's rounding)

    所谓银行家舍入法即“四舍六入法”,可以概括为:“四舍六入五考虑,五后非零就进一,五后皆零看奇偶,五前为偶应舍去,五前为奇要进一”

    val 1.5 1.50 1.51 1.55 1.59 2.5 2.50 2.51 2.55 2.59
    round(val) 2 2 2 2 2 2 2 3 3 3

    1.7 内置函数int()

    int(value, base=10)
    
    • value 可以被转换成int型整数的一个数或者一个字符串。
    • base 用于表示进制的数值。可以是2表示二进制、8表示八进制,16表示十六进制等。默认是10,表示转换成十进制的结果。
    (a) 当输入为一个数时

    可以是浮点数,也可以是整数。相比于math.ceil()、math.floor()、round()等函数而言运算比较简单粗暴,直接截断舍弃小数部分,返回整数部分。

    print(int(25.5))
    print(int(20.3))
    print(int(30.7))
    
    25	#int(25.5)
    20	#int(20.3)
    30	#int(30.7)
    
    (b) 当输入为字符串时
    print(int("11"))
    print(int("15"))
    
    print(int('1', 2))
    print(int('100', 2))
    
    print(int('7', 8))
    print(int('500', 8))
    
    print(int('A', 16))
    print(int('10', 16))
    
    11	#int("11")
    15 	#int("15")
    
    1 	#int('1', 2)
    4	#int('100', 2)
    
    7	#int('7', 8)
    320 	#int('500', 8)
    
    10 	#int('A', 16)
    16 	#int('10', 16)
    

    1.8 算术运算符//

    python文档中称之为floor division operator,直译过来即地板除,而且还特别声明了无论操作数是整型还是浮点型,都执行的是floor操作。

    print(5//2)
    print(5//2.0)
    print(5.0//2.0)
    print(5.0//-2.0)
    print(-5.0//2.0)
    print(-5.0//-2.0)
    
    2		#5//2
    2.0		#5//2.0
    2.0		#5.0//2.0
    -3.0		#5.0//-2.0
    -3.0		#-5.0//2.0
    2.0		#-5.0//-2.0
    

    1.9 内置函数eval()

    eval(expression[, globals[, locals]])
    

    该函数基本功能是将给定字符串当作有效表达式来求值,并返回计算结果。

    函数参数是字符串以及可选的全局。如果给出globals,则必须是以字典形式给出的全局变量集。
    locals可以是任何一种映射对象(mapping object)。

    如果给定输入是字符串,开头和结尾的空格及制表位都会被跳过。

    1.9.1 可以当作计算器使用
    x = 1
    eval('x+1')
    
    2	#eval('x+1')
    
    1.9.2 可以将list/tuple/dict与string相互转化
    • (a) 字符串转换成列表
    str_list = "[[1,2], [3,4], [5,6]]"
    type(str_list)
    list_from_str = eval(str_list)
    type(list_from_str)
    print(list_from_str)
    
    <class 'str'>	#type(str_list)
    <class 'list'>	#type(list_from_str)
    [[1, 2], [3, 4], [5, 6]]	#list_from_str
    
    • (b) 字符串转换成元组
    str_tup = "([1,2], [3,4], (5,6))"
    type(str_tup)
    tup_from_str = eval(str_tup)
    type(tup_from_str)
    print(tup_from_str)
    
    <class 'str'>
    <class 'tuple'>
    ([1, 2], [3, 4], (5, 6))
    
    • (c) 字符串转换成字典
    str_dict = "{1:'a', 2:'b', 3:'c'}"
    type(str_dict)
    dict_from_str = eval(str_dict)
    type(dict_from_str)
    print(dict_from_str)
    
    <class 'str'>
    <class 'dict'>
    {1: 'a', 2: 'b', 3: 'c'}
    
    • (d) 字典转换成字符串
    str_transfered_from_dict='dict_from_str'
    type(str_transfered_from_dict)
    print(str_transfered_from_dict)
    dict_from_transfered_str=eval(str_transfered_from_dict)
    type(dict_from_transfered_str)
    print(dict_from_transfered_str)
    
    <class 'str'>
    dict_from_str
    <class 'dict'>
    {1: 'a', 2: 'b', 3: 'c'}
    

    当然还有一些更高阶的用法,用到了再说。

    (全文完)


    参考资料

    [1] PYTHON中XRANGE和RANGE https://www.cnblogs.com/shixisheng/p/7089930.html

    [2] python lambda表达式 https://www.cnblogs.com/jydeng/p/4145188.html

    [3] What’s New In Python 3.0 https://docs.python.org/3/whatsnew/3.0.html

    [4] Python 3.x rounding behavior https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior

    [5] What is the difference between '/' and '//' when used for division? https://stackoverflow.com/questions/183853/what-is-the-difference-between-and-when-used-for-division

    [6] Python eval() https://www.programiz.com/python-programming/methods/built-in/eval

    [7] 为什么银行家舍入是合理的? https://blog.csdn.net/maozexijr/article/details/78563531

    [8] Round half to even https://en.wikipedia.org/wiki/Rounding#Round_half_to_even

    [9] Rounding rules https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules

    [10] 从“四舍五入”到“奇进偶舍” https://juejin.cn/post/6844904055953702919

    [11] 利息被银行四舍五入后,你到底是赚了还是亏了?答案和想的不太一样|把科学带回家 https://youwuqiong.top/10276.html

    本文作者 :phillee
    发表日期 :2021年12月20日
    本文链接https://www.cnblogs.com/phillee/p/15645127.html
    版权声明 :自由转载-非商用-非衍生-保持署名(创意共享3.0许可协议/CC BY-NC-SA 3.0)。转载请注明出处!
    限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。

  • 相关阅读:
    C#中的异常处理
    How to: Create a Windows Communication Foundation Client
    王立平--result += &quot;{&quot;;
    Gradle增量学习建筑
    android 当屏幕截图,你如何改变屏幕内容,他们俩bitmap将合并的图像被一起显示
    惊人go语言(image网站开发)
    树莓派的演奏音符3 -- LCD1602显示文章
    Linux解析内核源代码——传输控制块诞生
    Preemption Context Switches 和 Synchronization Context Switches
    folat i = 0.1; 警告
  • 原文地址:https://www.cnblogs.com/phillee/p/15645127.html
Copyright © 2011-2022 走看看