总结不易,且看且珍惜!
jupynotebook 基本操作
关于cell(代码块)快捷键
shift+enter
执行当前cell并在下面插入一个cell
ctrl + enter
只执行当前cell
alt + enter
只在下面插入一个cell
shift + tab
查看相关函数的参数
tab
代码补全
基本数据类型
Python标准数据类型:Numbers数字,String字符串,List列表,Tuple元祖,Dici字典
type()
函数,用于查看数据类型
print()
函数,用于输出/打印内容
1、数字
Numbers数字分为:int整型,long长整型,float浮点型,complex复数
x1 = 10
x2 = 10.0
print(type(x1),type(x2))
<class 'int'> <class 'float'>
2、布尔型
x4 = True
print(x4,type(x4))
print(True == 1)
print(False == 0)
print(True * 10)
#True实际值是1,False实际值是0
True <class 'bool'>
True
True
10
3、字符串
创建字符串,一定用英文标点符号.
单引号(''
) 双引号(""
)一样,三引号(''' '''
或""" """
)可以表示多行字符串
注意在str内部有str时不同引号交替使用,如 ’ hi,“xiaoming” ’
in:
str1 = 'hello1'
str2 = "hello2"
str3 = '''hello3
world'''
print(str1)
print(str2)
print(str3)
out:
hello1
hello2
hello3
world
字符串与其他类型一起输出 print()
a=100
in: print('考了',a,'分')
out: 考了100分
转义字符
\n
提行(另起一行)
in: print('提行\n提行')
out: 提行
提行
使转义字符失效—> ''
前加r , 即
in:print(r'提行\n提行')
out:提行\n提行
或者对相应符号如'
、\
等前面加\
字符串运算
print('hello'+'world')#加法连接
print('a'*10) #乘法重复
print('h'in 'hello','h' not in 'hello')#成员运算in,not in
常用字符串的函数、方法
len() 计算长度
print(len('12345')) # len() → 计算长度
str()/int()/float() 转化类型
print(str(12345),str(10.29)) # str() → 将数值型转换成浮点型
print(int('12345'),float('2008.12')) # int()/float() → 将浮点型转换成字符串
eval()函数:执行字符串中的内容
print(eval('100*20')) # eval() → 执行字符串中的内容
2000
.replave()方法:代替字符串
var1 = 'hello world'
print(var1.replace('l','L')) # .replace() → 替换
heLLo worLd
.splict()方法:形成列表
var2 = '小明,男,设计师'
print(var2.split(',')) # .split() → 分列,这里结果是一个列表list
['小明', '男', '设计师']
str.join():连接形成字符串,对象为列表
lst = ['poi01', '116.446238', '39.940166']
m = '-'
st = m.join(lst)
print(st)
poi01-116.446238-39.940166
str.startswith(“str”) 判断是否以“str”开头;str.endswith (“str”) 判断是否以“str”结尾
st = 'abcdefg'
print(st.startswith('a'), st.endswith('f'))
True False
字母大小写
st = 'aBDEAjc kLM'
print(st.upper()) # 全部大写
print(st.lower()) # 全部小写
print(st.swapcase()) # 大小写互换
print(st.capitalize()) # 首字母大写
ABDEAJC KLM
abdeajc klm
AbdeaJC Klm
Abdeajc klm
判断是否数字isnumeric()或字母isalpha()
st = '1234567'
print(st.isnumeric()) # 如果 string 只包含数字则返回 True,否则返回 False.
st = 'DNVAK'
print(st.isalpha()) # 如果 string 至少有一个字符并且所有字符都是字母则返回 True,否则返回 False
True
True
rstrip()删除字符末尾的空格
st = 'avd '
print(st.rstrip())
avd
格式化字符串(在字符串中插入变量)
方法:%
in:
var1 = 99
var2 = 99.9999
var3 = 'csdn'
print('这个班上一共有%i人' % var1) # %i:格式化整数
print('小明这次考了%f分' % var2) # %f:格式化浮点数字
print('小明这次考了%.2f分' % var2) # %.2f:这里表示保留两位小数,会自动四舍五入
print('现在我位于%s' % var3) # %s:格式化字符
print('这个班上一共有%i人,小明这次考了%f分,现在我位于%s' % (var1,var2,var3))#多次格式化
out:
这个班上一共有99人
小明这次考了99.999900分
小明这次考了100.00分
现在我位于csdn
这个班上一共有99人,小明这次考了99.999900分,现在我位于csdn
序列:列表、元组、字典
-
序列是Python中最基本的数据结构
-
序列中的每个元素都分配一个数字 - 它的位置,也称“索引”,第一个索引是0,第二个索引是1,依此类推。
-
Python有6个序列的内置类型,但最常见的是列表和元组。
-
列表list,元组tuple,字符串str都是序列
-
list是可变序列 (可以通过索引改变单个元素的值)
-
元组、字符串是不可变序列
-
字典是另一种可变容器模型,且可存储任意类型对象。
-
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中
-
键必须是唯一的,但值则不必。
4、列表(用[]包围 )→ list
in:
lst1 = [1,2,3,4,5,6]
lst2 = ['a','b','c','d']
lst3 = ['abc',123,10.2,[1,2,3,4]]
print(lst1)
print(lst2)
print(lst3)
print('这是一个列表:',lst1)
列表内元素可以是数字、字符串、列表(嵌套列表)
out:
[1, 2, 3, 4, 5, 6]
['a', 'b', 'c', 'd']
['abc', 123, 10.2, [1, 2, 3, 4]]
这是一个列表: [1, 2, 3, 4, 5, 6]
5、元组(用()包围 )→ tuple
in:
tup1 = (1,2,3,4,5,6)
tup2 = 'a','b','c','d' # 注意,元组不需要括号也可以
tup3 = ('abc',123,10.2,(1,2,3,4))
print(tup1)
print(tup2)
print(tup3)
out:
(1, 2, 3, 4, 5, 6)
('a', 'b', 'c', 'd')
('abc', 123, 10.2, (1, 2, 3, 4))
6、字典(用{}包围 )→ dict
Dict字典,用{}标识,由索引(key)和它对应的值value组成,无序对象
x7 = {"name":"cat", "city":"shanghai", "tel":10001000}
print(x7,type(x7))
x7["name"]
out:
{'tel': 10001000, 'name': 'fatbird', 'city': 'shanghai'} <class 'dict'>
'cat'
列表、元组运算操作
in:
print([1,2,3]+[4,5,6]) # 列表组合
print([1,2,3]*3) # 列表重复
print(5 in [2,3,4]) # 列表是否存在于表中
print(len(lst3)) # 求列表长度
out:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
False
4
字典的特点
dic = {'a':1,'b':2,'c':3}
#键与值,一定共同出现
dic = {'a':1,'a':2}
print(dic)
#同一个键不可出现两次:同一个键被赋值两次,后一个值会被记住
dic = {'var1':1, 'var2':'hello', 'var3':[1,2,3], 'var4':{'a':1,'b':2}}
#key必须是不可变对象,value则可以是任意对象:数值,字符串,序列,字典
print(dic)
#字典是一个无序集合,序列由于没有key来做对应,所以以顺序来对应值
#序列有顺序,字典没有!
{'a': 2}
{'var1': 1, 'var2': 'hello', 'var3': [1, 2, 3], 'var4': {'a': 1, 'b': 2}}
字典的添加与删除
dic['var5'] = '添加一个值' # 任意添加元素
dic['var4'] = '任意修改其中一个值' # 任意修改元素
del dic['var1'] # 任意删除元素
print(dic)
dic.clear() # 清空词典所有条目
print(dic)
del dic # 删除词典
#print(dic)
{'var2': 'hello', 'var3': [1, 2, 3], 'var4': '任意修改其中一个值', 'var5': '添加一个值'}
{}
申明一个字典
dic = {'a':1,'b':2}
#最简单直接的方式
dic = dict(m = 10 ,n = 'aa', h = [1,2,3])
print(dic)
#dict()函数
lst1=[("a","fff"),("b","ggg")]
lst2=[["c",1],["d",2]]
lst3=(("e",[1,2]),("f",[3,4]))
dic1 = dict(lst1)
dic2 = dict(lst2)
dic3 = dict(lst3)
print(dic1,dic2,dic3)
#dict()由序列生成一个字典,嵌套序列,可以是list或者tuple
keys = ["a", "b", "c"]
dic1 = dict.fromkeys(keys)
dic2 = dict.fromkeys(keys, 'hello')
print(dic1,dic2)
#只有key,直接生成一个字典
{'n': 'aa', 'h': [1, 2, 3], 'm': 10}
{'a': 'fff', 'b': 'ggg'} {'d': 2, 'c': 1} {'f': [3, 4], 'e': [1, 2]}
{'c': None, 'a': None, 'b': None} {'c': 'hello', 'a': 'hello', 'b': 'hello'}
字典常用操作
dict.**update()**方法:更新/合并一个字典,把第二个字典合并到第一个字典,改变了第一个字典
dic1 = {"a":1, "b":2}
dic2 = {"c":3, "d":4}
dic1.update(dic2)
print(dic1,dic2)
{'a': 1, 'c': 3, 'd': 4, 'b': 2} {'c': 3, 'd': 4}
单纯复制(地址不变)
a = {'m':1 , 'n':2 , 'p':3}
b = a
a.update({'q':4})
print(a,b)
#和序列的原理一样,a和b指向同一个字典,所以会一起更新
{'n': 2, 'q': 4, 'm': 1, 'p': 3} {'n': 2, 'q': 4, 'm': 1, 'p': 3}
.copy()复制(改变地址)
a = {'m':1 , 'n':2 , 'p':3}
b = a.copy()
a.update({'q':4})
print(a,b)
#通过.copy()方法,复制一个新的字典
{'n': 2, 'q': 4, 'm': 1, 'p': 3} {'m': 1, 'n': 2, 'p': 3}
len(dic)查看元素个数
print(len(a))
#查看字典元素个数
4
成员包含(使用key)
print('m' in a)
print(1 in a)
#in / not in :判断是否包含,这里的判断对象是key
True
False
字典的元素访问
dic = {'a':1, "b":2, "c":3}
print(dic['a'])
#print(dic[1]) # 不能用序列的索引方式
#字典里面也就同样的意思,但字典没有顺序,以key来作为指向,所以指向的key必须存在
poi = {'name':'shop', 'city':'shanghai', 'information':{'address':'somewhere', 'num':66663333}}
print(poi['information']['address'])
#对于嵌套字典,输出嵌套内容,通过重复指向来输出
print(poi.get('name'))
print(poi.get('type',print('nothing')))
#.get(key)方法:直接查看key的value,如果没有相应key则返回None,添加print参数可以多返回一个值
print(poi.keys(),type(poi.keys()))
print(list(poi.keys()))
#.keys()方法:输出字典所有key,注意这里的输出内容格式是视图,可以用list()得到key的列表,类似range()
print(poi.values(),type(poi.values()))
print(list(poi.values()))
#.values()方法:输出字典所有values,原理同.keys()方法
print(poi.items(),type(poi.items()))
print(list(poi.items()))
#.items()方法:输出字典所有items(元素),原理同.keys()方法
1
somewhere
shop
nothing
None
dict_keys(['information', 'name', 'city']) <class 'dict_keys'>
['information', 'name', 'city']
dict_values([{'address': 'somewhere', 'num': 66663333}, 'shop', 'shanghai']) <class 'dict_values'>
[{'address': 'somewhere', 'num': 66663333}, 'shop', 'shanghai']
dict_items([('information', {'address': 'somewhere', 'num': 66663333}), ('name', 'shop'), ('city', 'shanghai')]) <class 'dict_items'>
[('information', {'address': 'somewhere', 'num': 66663333}), ('name', 'shop'), ('city', 'shanghai')]
字典的元素遍历
poi = {'name':'shop', 'city':'shanghai', 'information':{'address':'somewhere', 'num':66663333}}
for key in poi.keys():
print(key)
print('-------')
for value in poi.values():
print(value)
print('-------')
for (k,v) in poi.items():
print('key为 %s, value为 %s' %(k,v))
print('-------')
#for函数遍历
information
name
city
-------
{'address': 'somewhere', 'num': 66663333}
shop
shanghai
-------
key为 information, value为 {'address': 'somewhere', 'num': 66663333}
key为 name, value为 shop
key为 city, value为 shanghai
-------
索引 ( [ ] )(筛选单个数)
元组、字符串索引和列表一样
in:
lst = [1,2,3,4,5,[1,2,3,4]]
print(lst)
print(lst[0],lst[1])
print(lst[-1],lst[-2])
#python索引从0开始
#lst[-1]代表最后一个元素
tup = ('a','b','c','d',('hello','world'))
print(tup)
print(tup[2],tup[-1])
st = 'hello world'
print(st[0],st[2],st[-1])
out:
[1, 2, 3, 4, 5, [1, 2, 3, 4]]
1 2
[1, 2, 3, 4] 5
('a', 'b', 'c', 'd', ('hello', 'world'))
c ('hello', 'world')
h l d
切片 ( [ : ] )(筛选单个区间)
切片是左闭右开
in:
print(lst[2:3]) # 索引2至索引3,但不包含索引3
print(lst[:2]) # 从索引0至索引2,但不包含索引2
print(lst[1:]) # 从索引1至最后一个元素,包含最后一个元素
print(lst[1:-1]) # 从索引1至最后一个元素,不包含最后一个元素
print(st[1:])
print(st[:-2])
print(tup[2:5])
out:
[3]
[1, 2]
[2, 3, 4, 5, [1, 2, 3, 4]]
[2, 3, 4, 5]
ello world
hello wor
('c', 'd', ('hello', 'world'))
步长 ( [ : : ] )(跳着筛选某个区间)
lst[a: b :n] → 对于lst序列,从索引a至索引b,但不包含索引b,其中间隔为n(步长)
in:
lst = [10,20,30,40,50,60,70,80,90]
print(lst[::2])
out:
[10, 30, 50, 70, 90]
列表与生成器
print(range(5),type(range(5)))
#range()是生成器,指向了一个范围
#range(5)代表指向了0,1,2,3,4这几个值
#range(2,5)代表指向了2,3,4这几个值,注意这里不是使用:
#range(0,10,2)代表指向了0,2,4,6,8这几个值,最后的2代表步长
lst = list(range(5))
print(lst)
#通过list()函数生成列表
list的常用函数与方法
lst = [10,20,30,40,50,60,70,80,90]
len(): 求长度,个数
print(len(lst))
9
lst.append():列表末尾添加新的元素,添加本身
lst.append(100)
lst.append(['a','b'])
print(lst)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, ['a', 'b']]
lst.extend():末尾添加另一个序列中的所有元素(用新列表扩展原来的列表),添加子集
lst.extend(['a','b'])
print(lst)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, ['a', 'b'], 'a', 'b']
lst.insert():这里是在索引i(2)的位置,插入值m(1000)
lst.insert(2,1000)
print(lst)
[10, 20, 1000, 30, 40, 50, 60, 70, 80, 90, 100, ['a', 'b'], 'a', 'b']
删除元素
lst.remove()方法:移除列表中某个值的第一个匹配项
lst = ['Jack','Jack','Tom','Tracy','Alex','White']
lst.remove('Jack')
print(lst)
['Jack', 'Tom', 'Tracy', 'Alex', 'White']
del语句:删除list的相应索引值
del lst[3:5]
print(lst)
['Jack', 'Tom', 'Tracy']
.clear()#移除所有值
lst.clear()
print(lst)
[]
.copy():复制列表,换新id(地址)
lst2 = lst
lst3 = lst.copy()
print(lst,id(lst))
print(lst2,id(lst2))
print(lst3,id(lst3))
#复制列表,注意指向问题
[10, 20, 1000, 30, 40, 50, 60, 70, 80, 90, 100, ['a', 'b'], 'a', 'b'] 2640459676808
[10, 20, 1000, 30, 40, 50, 60, 70, 80, 90, 100, ['a', 'b'], 'a', 'b'] 2640459676808
[10, 20, 1000, 30, 40, 50, 60, 70, 80, 90, 100, ['a', 'b'], 'a', 'b'] 2640459676936
其他
max() 、min() 、sum()
.index() 、.count()
lst = [1,2,3,4,5,6,7,8,9,0]
print(max(lst),min(lst),sum(lst)) # 返回列表的最大值、最小值、求和,这三个函数都只针对数字的list
print(lst.index(3)) # .index(obj)方法:从列表中找出某个值第一个匹配项的索引位置
lst = [1,1,2,3,3,4,4,4,4,5,6]
print(lst.count(4)) # .count(obj)方法:计算值的出现次数
9 0 45
2
4
变量
方程式“=”左边的,就是变量
- 给变量赋值即创建该变量,并且同时赋予该变量 → ① 变量名、② 变量类型
- 变量命名规则①:变量名第一个字符必须是字母(大小写均可)或者下划线(“_”),不能数字开头;
- 变量命名规则②:变量名不能和常用功能性名字重合,例如print,if,for
- 变量命名规则③:不要有空格
运算符
算数运算符
a, b, c = 21, 10, 0
c = a * b # 乘法
print( "a乘b 的值为:", c )
c = a / b # 除法
print( "a除b 的值为:", c )
c = a % b # 取模,返回除法的余数
print( "a取b的模为:", c)
#修改变量 a 、b 、c
a, b, = 2, 3
c = a**b # 幂
print( "2的3次方的值为:", c)
a, b = 10, 4
c = a//b # 取整除数
print( "10除4的整除数为:", c)
a乘b 的值为: 210
a除b 的值为: 2.1
a取b的模为: 1
2的3次方的值为: 8
10除4的整除数为: 2
逻辑运算符
and
(不同于c的 &&)
or
(不同于c的 ||)
not
(不同于c的 !)
比较运算符
== 、 != 、 >= 等(与c相同)
成员运算符
lst = [1,2,3,4,5,6]
a,b = 1,10
print(a in lst) # a 在 lst 序列中 , 如果 x 在 y 序列中返回 True。
print(b not in lst) # b 不在 lst 序列中 , 如果 x 不在 y 序列中返回 True。
注释(#单行注释,’’’ ‘’'多行注释)
- 注释是用来说明代码
- 程序运行的时候,Python解释器会直接忽略掉注释 → 有没有注释不影响程序的执行结果,但是影响到别人能不能看懂你的代码。
- 但“#”不只代表注释,还代表某些文件的特殊格式,写在脚本开头
- 注意:注释只在脚本中起作用
条件语句
Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块
if...
if...else...
if...elif...elif...else...
注意缩进问题
- 回车自动缩进,如果要改变缩进用tab
- 同一个缩进的代码组成一个代码块
例子
number = int(input('请输入一个整数:'))#input进来的都是str
if number < 10:
print('该数字小于10')
elif number == 12:
print('该数字居然恰恰等于12')
elif number == 20:
print('该数字居然恰恰等于20')
else:
print('反正这个值大于10')
循环语句
for循环 → for循环常用于遍历,比如list、str和字典(明确循环次数)
#分别查看学生名字
students = ['小明','小红','小李子']
for i in students:
print('这个学生的名字是%s' % i)
这个学生的名字是小明
这个学生的名字是小红
这个学生的名字是小李子
#遍历字典
age = {'Tom':18, 'Jack':19, 'Alex':17, 'Mary':20}
for name in age:
print(name + '年龄为:%s岁' % age[name])
Tom年龄为:18岁
Jack年龄为:19岁
Alex年龄为:17岁
Mary年龄为:20岁
**for i,j in zip(lst1,lst2) #i,j分别是序列lst1,lst2的索引**
#for循环加判断语句
for letter in 'Python':
if letter == 'h':
print( '该字母是h')
else:
print( '该字母是不是h')
该字母是不是h
该字母是不是h
该字母是不是h
该字母是h
该字母是不是h
该字母是不是h
#嵌套循环
for i in range(3): #range()函数可创建一个整数列表,一般用在 for 循环中
for j in range(2):
print(i,j)
0 0
0 1
1 0
1 1
2 0
2 1
while循环
- 执行语句可以是单个语句或语句块
- 判断条件可以是任何表达式,true(任何非零、或非空(null)),循环继续。
- 当判断条件假false时,循环结束。
例子
count = 0
while count < 9:
print( 'The count is:', count)
count = count + 1
print( "Good bye!")
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
循环控制语句
break:在语句块执行过程中终止循环,并且跳出整个循环
continue:在语句块执行过程中跳出该次循环,执行下一次循环
pass:pass是空语句,是为了保持程序结构的完整性
pass语句
for letter in 'Python':
if letter == 'h':
pass
print( '当前字母 : h,但是我pass了')
print( '当前字母 :', letter)
print( "Good bye!")
#pass是空语句,是为了保持程序结构的完整性。(不中断也不跳过)
当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h,但是我pass了
当前字母 : h
当前字母 : o
当前字母 : n
Good bye!
函数
- 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
- 函数用def语句定义
- 函数用return来返回值
有参数
def f1(n,m):
lstf = []
for i in range(n):
lstf.append(m)
return lstf
#定义好函数,其中有两个参数 → n代表个数,m代表元素值
#同时注意,这里的lstf是局部变量
print(f1(10,'a'))
print(f1(5,'helloworld'))
print(f1(3,[1,2,3]))
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
['helloworld', 'helloworld', 'helloworld', 'helloworld', 'helloworld']
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
无参数
def f2():
print('hello world')
#定义好函数,这里并没有输入参数
f2()
#执行函数
hello world
可变参数
def f(*x):
print(x)
return x
f(1)
f('a','b')
f(1,2,3,[44,33])
print(type(f('a','b')))
#通过*来定义可变参数
#默认会把可变参数传入一个元祖!
(1,)
('a', 'b')
(1, 2, 3, [44, 33])
('a', 'b')
<class 'tuple'>
Lambda
- lambda表达式是起到一个函数速写的作用
- lambda的主体是一个表达式,而不是一个代码块。
- lambda只有一行,仅仅能在lambda表达式中封装有限的逻辑进去。
示例
def fun(a,b,c):
return a+b+c
print(fun(2,3,4))
9
#上面为自定义,下面是lambda
f = lambda a,b,c:a+b+c
print(f(2,3,4))
9
局部变量及全局变量
- 定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。
- 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中
- global语句 → 把局部变量变为全局变量
模块
Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句
创建一个模块,包含一个阶乘函数f1(n)、一个列表删值函数f2(lst,x),一个等差数列求和函数f3(a,d,n)
def f1(n):
y = 1
for i in range(1,n+1):
y = y * i
return y
#创建阶乘函数f1(n)
def f2(lst,x):
while x in lst:
lst.remove(x)
return lst
#创建列表删值函数f2(lst,x)
def f3(a,d,n):
an = a
s = 0
for i in range(n-1):
an = an + d
s = s + an
return s
#创建等差数列求和函数f3(a,d,n)
#创建模块testmodel2,包括三个函数
模块路径问题
import pandas
print(pandas.__file__)
#查看现有包所在路径,将自己创建的包存入路径
C:\Users\iHJX_Alienware\Anaconda3\lib\site-packages\pandas\__init__.py
# 加载sys包,把新建的tsmodel所在路径添加上
import sys
sys.path.append('C:/Users/iHJX_Alienware/Desktop/')
import tsmodel2
tsmodel2.inf()
print(tsmodel2.fun(2,3))
hello world!
6
调用模块
import tsmodel1
print(tsmodel1.f1(5))
print(tsmodel1.f2([2,3,4,5,5,5,6,6,4,4,4,4],4))
print(tsmodel1.f3(10,2,10))
#直接用import调用模块,.f1()调用模块函数(方法)
120
[2, 3, 5, 5, 5, 6, 6]
180
简化模块名:import…as…
import tsmodel1 as tm1
print(tm1.f1(5))
120
调用部分模块语句:From…import 语句
from tsmodel1 import f2
print(f2([2,3,4,5,5,5,6,6,4,4,4,4],4))
#print(f3(10,2,10))
#单独导入模块的部分功能,但无法使用其他未导入模块功能
[2, 3, 5, 5, 5, 6, 6]
python标准模块 —— random随机数
import random
x = random.random()
y = random.random()
print(x,y*10)
#random.random()随机生成一个[0:1)的随机数
m = random.randint(0,10)
print(m)
#random.randint()随机生成一个[0:10]的整数
st1 = random.choice(list(range(10)))
st2 = random.choice('abcdnehgjla')
print(st1,st2)
#random.choice()随机获取()中的一个元素,()种必须是一个有序类型
lst = list(range(20))
sli = random.sample(lst,5)
print(sli)
#random.sample(a,b)随机获取a中指定b长度的片段,不会改变原序列
lst = [1,3,5,7,9,11,13]
random.shuffle(lst)
print(lst)
#random.shuffle(list)将一个列表内的元素打乱
0.2199425772246426 9.964090615405606
10
7 e
[17, 7, 16, 3, 5]
[9, 5, 3, 13, 1, 11, 7]
python标准模块 —— time时间模块
import time
for i in range(2):
print('hello')
time.sleep(1)
#time.sleep()程序休息()秒
print(time.ctime())
print(type(time.ctime()))
#将当前时间转换为一个字符串
print(time.localtime())
print(type(time.localtime()))
#将当前时间转为当前时区的struct_time
#wday 0-6表示周日到周六
#ydat 1-366 一年中的第几天
#isdst 是否为夏令时,默认为-1
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
#time.strftime(a,b)
#a为格式化字符串格式
#b为时间戳,一般用localtime()
hello
hello
Wed Jul 31 17:33:18 2019
<class 'str'>
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=31, tm_hour=17, tm_min=33, tm_sec=18, tm_wday=2, tm_yday=212, tm_isdst=0)
<class 'time.struct_time'>
2019-07-31 17:33:18