python小白学习之旅3
本篇文章写完也就意味着我们将进入pycharm领域的学习了,jupyter的学习告一段落。上节讲到format函数的使用,下面接着。
1.str的内置函数
查找类: find()函数--查找功能,查找字符串中是否有子串例如s.find(s1,25),从25个字
开始找s中是否有s1。 index函数功能与其类似,用法一样,但是index函数会在检索不到的时候报错flase。
判断类: islower()、isupper(0分别是判断字符是小写还是大写,返回一个布尔值。 isalpha ()判断是否是字母。 startwith()、endwith(0是判断是否以什么开头、结尾的函数
操作类: s.strip('xxxx')--删除字符类。 format 格式化赋值 join拼接字符串 eval()函数--把一个字符串当作一个表达式执行返回执行后的结果,比如eval('3 + 4') exec()函数类似,但是不会返回结果。
2.list列表(用[ ]来囊括)
首先,列表里面的内容是有顺序的,但是内容可以不是一个类型的。可以用type()函数判断类型。
list的常见操作有print(L[1:5:2])---输出第1位到第5位,幅度是2.同时规定: 若按尾到头来输出,则最后一位下标为 -1。常见的list函数有:append()函数---在末尾插入一个设定的内容比如 a = [1,2,3], a = append(2,10)--在下标2的数字后面加入数字10; insert()函数---a.insert(插入的位置值,插入的数据) ; remove()函数--a.remove(666).删除指定的值,,del()也是删除特定位置的函数; reverse()函数--a.reverse()为翻转函数,是永久性的反转但是可以再次用reverse反转过来; replace()为替换函数;extend()函数---为扩展函数,直接把一个列表接在上一个列表; sort()函数为对列表进行按照字母大小的永久性排序;sorted()为对列表进行临时排序; count()函数---a.count(6)为查找表中6的元素个数; copy()函数--传值不传址的浅拷贝,深拷贝需要用到特定的工具; 列表可以进行+ 列表相加 *列表元素重复打印,也可以进行双列表循环的操作:
a = [['one',1], ['two',2], ['three',3]] for k,v in a: print(k,'----',v) #双层列表循环,同时列表之间可以嵌套,以及使用一些if之类的语句
关于如何修改列表中的值,我们可以直接用a[2]="...."直接赋值便改变了索引,同理 del a[n]也可以删除某个列表数据。值得一提的是pop()函数可以提取被删除的值,在实际工程中比如攻击目标被摧毁后需要在原地有一个爆炸烟花就需要这种手段了。下面是简单的代码演示
a = ["i" , "love" , "money"] b = a.pop() print(a,end = " 删除后的列表\n") print(b,end = " 已删除的元素")
对于数字列表的话,双*代表平方,可以简单的使用min() max() sum()函数;sometimes学会建立一个空数字列表,然后后期利用append()函数将数值代入,可以顺利得到一个全新的数字列表。下面介绍一下列表解析的写法:
num = [value**2 for value in range(1,5)] print(num) # 列表解析规则使得=代码变得更加简洁
另外,列表[:]表示列表元素从头到尾遍历,而[5:]是第五个元素到最后一个元素,类似的可以类推。运用这种元素的遍历法我们可以很好地写出复制,遍历,切片的功能。
3.tuple元组(数组,用()来囊括)
简而言之就是不可更改的list,无序,比如 t = (1,2,3,4,5),同理可以使用len max min index extend in 、not in、id remove del等函数,其中交换值的函数为 a,b = b, a;调用元祖元素是集合名+[ ]+方框中写好序号比如a[2] 来调用。如果要修改元素只能重新赋值。
4.set集合(数组,用{ }来囊括)
无序,内部数据有唯一性质,无法使用索引和分片。有add clear 函数remove报错 discard函数不报错 pop函数---随机移除一个函数 intersection--交集 difference--差集 union--并集 issubset--是否为子集 issuperset--是否为超集 frozon set--不能进行任何修改的集合。
5.dict字典(用{}囊括键-值对的形式出现)
组合数据,以键值对的形式出现。----序列类型,无分片和索引。
d = {'one': 1, 'two': 2}
print(d)
del(d['one']) # 此时把one 看做列表值,数字不用打引号,但是字符串需要打引号
# 附加:通过字典设置参数,需要解包
s = 'we are {personal_name},website is {url},teacher is {sb}'
s_dict = {'personal_name': "lhs", 'url': "www.uestc.edu.cn", 'sb': "lhs"}
s = s.format(**s_dict) # 解包操作
print(s)
# 以下是dict的几种命名形式
d1 = {}
print(type(d1),end = 'd1 none')
print()
# 空字典2
d2 = dict()
print(type(d2),end = 'd2 none')
print()
# 1创建键值数据,第一类用大括号,注意字符型要用引号带上:
d3 = {'name ':'lhs', 'old':18, 'husbnd':'tj'}
print(type(d3),end = 'd3')
print()
print(d3)
# 2.1创建键值数据,第二类用dict创建有内容字典,本质用dict包围了d3:
d4 = dict({'name ':'lhs', 'old':18, 'husbnd':'tj'})
print(type(d4),end = 'd4')
print()
print(d4)
# 2.2创建键值数据,第三类dict创建有内容字典,利用关键字参数
d5 = dict(name = 'lhs', old = 18, husbnd = 'tj')
print(type(d5),end = 'd5')
print()
print(d5)
# 2.3创建键值数据,第三类dict创建有内容字典,利用关键字参数
d6 = dict([('name','lhs'),('old',18),('husbnd','tj')])
print(type(d6),end = 'd6')
print()
print(d6) # summary: 字典的调用和列表类似了
关于键值对的删除,直接del a["name"] 即可,注意:1、删除的就永久删除了,至于改变元素值最简单的就是a["age"] = a["age"] +15这样了。2、python不关心键值对的存储顺序,只关系键值之间的关联关系。3、如果是遍历所有的键,舒服点的代码就是for m in zidianming.keys()其中keys()方法可以省略,若是遍历键值就是把keys()换成values()。
字典列表用法如下:
1 a_0 = {"color" : 'green' , "points": 5} 2 a_1 = {"color" : 'black' , "points": 6} 3 a_2 = {"color" : 'red' , "points": 7} 4 a_3 = [a_0 , a_1, a_2] 5 for ax in a_3: 6 print(ax) # 还有方法就是建立一个新的列表,再利用append函数插入一个有值的字典。
在字典中存储列表:
pizza = { "scale" : "big" , "toppings": ["mushroom", "extra cheese"]} print(pizza["scale"]) for t in pizza["toppings"]: print(t)
在字典中存储字典:
users = {"anrys": {"first": "tian", "last": "anrys", "location": "Yibin"}, "long": {"first": "li", "last": "xiaolong", "location": "mianyang"}} for username, user_info in users.items(): print("username :"+ username) full_name = user_info['first']+ " " + user_info["last"] location = user_info["location"] print("\tfull name : " + full_name.title()) print("\tlocation: " + location.title())
6.变量作用域
glaobal:全局变量,在函数外部定义 local:局部变量,在函数内部定义 其中变量只能内部访问外部,不能外部访问内部
7补充
1:函数文档的查询与设置
def stu(name , age, *args): '''this is a text 填充需要的文本信息 '''' print('scss')#可以用stu._doc 或者help(stu)查看文档信息
2.混合参数的调用
# 混合参数 def stu(name, age, hobby = 'no', *args, **kwargs): print('Hello, ladies and gentlemen. First things first, let me introduce myself briefly.') print('My name is {0},and my old is {1}'.format(name, age)) if hobby =='no' : print('I amm so sorry, I don\'t have hobby') else: print('My hobby is {0}'.format(hobby)) print('*'*20) for i in args: print(i) for k,v in kwargs.items(): print(k,'------',v) name = 'lhs' age = '18' hobby = 'swimming' stu(name, age, hobby ) print('-'*30) stu(name, age, hobby, roommate1 = 'jyb', roommate2 = 'lby', roommate3 = 'hhb', hobby1= 'basketball', hobby2 = 'chat with lhs')
关于while循环,补充几点: break为跳出循环,continue为继续循环;在不小心进入无限循环时,用ctrl加c或者关闭终端窗口都是行之有效的方法; 先定义空字典或列表,再添加进去新的内容也是很好的;以下补充代码是传递任意数量的实参
def make_pizza(*toppings): #创建一个名为toppings的空数组 print(toppings) make_pizza("tommato") make_pizza("mushroom" , "green peppers" , "extra cheese")
8 函数
简单的定义函数如下:
def greet_num(user): print("Wlcome " + user.title() + " !") greet_num("lhs") #直接就是简单的定义函数及其应用,注意进阶的就是在第一行代码处再加一个形参,调用时候要有对应顺序的写入两个实参即可。如果实在不想注意顺序,直接用user="lhs"即可,这叫关键字实参。
如果在定义函数的时候就指定了形参的值。这叫默认值。当然默认值可以根据后续的实参更改,关键字实参意思是键值对的形式,注意上述的所有类型的参数都可以混合使用;
有一种自定义函数很方便实际操作这就是传递列表函数在函数中间还可以利用append()函数后者pop函数进行函数的改变
def greet_users(names): for name in names: msg = "hello," + name.title() + "!" print(msg) usernames = ["lily" , "thy" , "ndf"] greet_users(usernames) # 此代码为传递列表函数
改变列表的案列如下:
def print_model(unprinted_one , completed_two): while unprinted_one: current_three = unprinted_one.pop() print(current_three) completed_two.append(current_three) def show_completed_models(completed_two): for completed_two in completed_two: print(completed_two) unprinted_one = ["1" , "2" ,"3" , "4"] completed_two = [] print_model(unprinted_one , completed_two) show_completed_models(completed_two) # 同时也可以用append函数及一些其他的函数。