☞鱼丶鱼 2019 年 11 月 14日
1、此时python无法识别age给出的值是 23 或2 和3
用str()函数将非字符串值表示为字符串:message = “Happy” + str(age) ,可以避免这个错误。
2、python2 和python3 关于整数除法
python 2 :
不使用浮点数格式的时候,结果直接舍弃小数部分;
python 3:
使用或不使用浮点数格式,结果都会精确到指定的小数点后位数;
精度问题
len()函数:打印列表长度
aaa = [“1”,“2”]
len(aaa)
print (len(aaa))
range()函数:指定范围、指定步长
指定范围:【
for chen in range(1,10)
print(chen) //输出的是1,2,3,4,5,6,7,8,9;没有10
】
指定步长:【
chen_numbers = list ( range ( 2 , 11 ,2 ) ) //从2开始每次加2,直到等于或大于11
print (chen_numbers) //结果为 : [2,4,6,8,10]
】
Decimal模块:
decimal模块(17位精度以上):
查看当前decimal模块精度,在shell中和在 . py中一样:
【
from decimal import *
print (getcontext())
】
修改成自己想要的精度,在shell中和在 . py中一样:
【
from decimal import *
getcontext(). prec = 50
】
输出:
在shell中直接写的情况下:
【
from decimal import *
a = Decimla (1)/ Decimla (3)
a
】
Round用法:
round用法(17位精度内):
(1)只有一个数作为参数,不指定位数:
返回一个整数(四舍五入原则),但当出现 .5 的时候是向整数取整(eg : 2.5 就取 2)
(1)指定取舍的小数位时:
取舍位前的小数位是偶数 : 向上取舍
取舍位前的小数位是奇数 : 直接舍弃
【eg : round(2.655 ,2)中 . 65为奇数,直接舍弃 最后一位 . 005,得出 2.65】
【eg : round(2.665 ,2)中 . 66为偶数,向上取舍 得出 2.67】
列表
带有指定元素或不带元素的空列表:
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]
a = []
使用索引访问列表中的元素:
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]
print (bicycle【0】) //python中的索引从 0 开始
使用索引【-1】访问列表中的最后一个元素:
love = [“l”,“o”,“v”,“e”]
print (love[-1]) //输出列表中的最后一个元素 : e
提取、使用列表中的元素值:
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]
message = "My first bicycle was a " + bicycles[0].title() + “.” //输出 My first bicycle was a Trek(title方法将指定元素首字母大写)
print(message)
修改、删除和添加元素:
(1)修改:
motorcycles = [‘1’, ‘2’, ‘3’]
print(motorcycles)
motorcycles[0] = ‘11’
print(motorcycles) // [‘11’, ‘2’, ‘3’]
(2)添加:
motorcycles = [‘1’, ‘2’, ‘3’]
print(motorcycles)
motorcycles.append(‘1’)
print(motorcycles) // [‘1’, ‘2’, ‘1’]
(3)插入:
aaa = [“1”,“2”,“3”,“4”,“5”]
print (aaa)
aaa.insert( 6 , “6”)
print (aaa) // [“1”,“2”,“3”,“4”,“5”,“6”]
(4)删除:
aaa = [“1”,“2”]
del aaa[0]
print (aaa) //[“2”]
方法
变量名.title()------------------------------->将变量中每个单词以首字母大写输出
变量名.lower()------------------------------->将变量中每个单词以首字母大写输出
变量名.rstrip()--------------------------------->去除字符串中处于 最后 的空格
变量名.lstrip()--------------------------------->去除字符串中处于 开头 的空格
变量名.strip()--------------------------------->去除字符串中处于 两端 的空格
变量名.insert(0 ,“元素名”)--------------------------------->向指定位置插入元素
del 变量名【索引】----------------------------------------------->删除指定索引位置的元素
pop()方法:弹出列表中指定索引位置的元素,使用过后列表中该元素被永久删除
old_aaa = [“1”,“2”,“3”]
new_aaa = old_aaa.pop(0)
print (new_aaa) // 1
remove()方法:按元素名称删除列表中的元素
aaa = [“1”,“2”,“3”]
new_aaa = aaa.remove(‘1’)
print (aaa) // 【“2”,“3”】
remove 和 pop 的区别:
使用del删除的元素不能被再次使用,使用pop()删除的元素可以被再次使用。
eg:aaa = [“1”,“2”]
del aaa[]