python基础汇总(六)

这是最后一篇python基础汇总了。

在进入正题之前,忍不住唠叨一句:

python的前途越来越光明,随着马云的无人酒店,无人海底捞陆续面世,python重要性越来越大。

未来是属于人工智能的,完成人工智能的代码是python自动化代码。

我们先来复习一下列表和字典的一些基础知识。

一.列表

ten_things="Apples Oranges Crows Telephones Light Sugar"

print("Wait there's not 10 things in that list,let's fix that.")

stuff=ten_things.split(' ') #spilt函数的作用,我已经在前面解释过了,猜猜是啥?
more_stuff=["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]

while len(stuff) !=10:
next_one =more_stuff.pop()
print("Adding: ",next_one)
stuff.append(next_one)
print("There's %d items now."%len(stuff))

print("There we go: ",stuff)

print("Let's do some things with stuff.")

print(stuff[1])
print(stuff[-1])
print(stuff.pop())
print(' '.join(stuff))
print('#'.join(stuff[3:5]))
输出结果:

Wait there's not 10 things in that list,let's fix that.
Adding: Boy
There's 7 items now.
Adding: Girl
There's 8 items now.
Adding: Banana
There's 9 items now.
Adding: Corn
There's 10 items now.
There we go: ['Apples', 'Oranges', 'Crows', 'Telephones', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephones Light Sugar Boy Girl Banana
Telephones#Light



'''
最后两句的作用需要弄清楚。
' '.join(stuff)的作用可以理解为join(' '.things),也就是说:
在join函数中,用空格将stuff列表的所有元素取出来并分隔开来。
如果是'%'.join(stuff),输出结果则是:
Apples%Oranges%Crows%Telephones%Light%Sugar%Boy%Girl%Banana
为什么没有corn,是因为在之前已经pop弹出去了
'''

还记得split()函数吗?-split函数是拆分字符串函数的操作,拆分成列表的形式。其中split()括号内的内容不可以为空,必须输入拆分点。
比如,"i love you yan pao pao",这个字符串:如果要拆分这个句子,是不是以空格为拆分点,将单词全部拆分开来?所以处理这句话,应该是split('  '),将拆分点用引号表示出来。
输出自然是['i','love','you','yan','pao','pao']。

那么,如果要拆分"www.baiidu.com"这个字符串?这时候拆分点是不是一个英文句号?所以应该这么处理,split(" . ") 

输出结果自然是["www","baidu","com"]

这段代码我们可以学到两个重要的知识点:

①split(' ')函数,分割字符串的操作,目前是使用空格分割。

②' '.join(list)函数,括号内是以list形式存在的变量。

二.字典

#create a mapping of state to abbreviation
states={
'Oregon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI'
}

#create a basic set of states and some cities in them
cities={
'CA':'San Francisco',
'MI':'Detroit',
'FL':'Jacksonville'
}

#add some more cities
cities['NY']='New York'
cities['OR']='Portland'

#print out some cities
print('-'*10)
print("NY state has: ",cities['NY'])
print("OR state has: ",cities['OR'])

#print some states
print('-'*10)
print("Michigan's abbreviation is: ",states['Michigan'])
print("Florida's abbreviation is: ",states['Florida'])

#do it by using the state then cities dict
print('-'*10)
print("Michigan has: ",cities[states['Michigan']])
print("Florida has: ",cities[states['Florida']])

#print every state abbreviation
print('-'*10)
for state,abbrev in states.items():
print("%s is abbreviated %s."%(state,abbrev))

#print every city in state
print('-'*10)
for abbrev,city in cities.items():
print("%s has the city %s."%(abbrev,city))

#now do both at the same time
print('-'*10)
for state,abbrev in states.items():
print("%s state is abbreviated %s and has city %s"%(state,abbrev,cities[abbrev]))

print('-'*10)
#safely get a abbreviation by state that might not be there
state=states.get('Texas',None)

if not state:
print("Sorry,no Texas.")

#get a city with a default value
city=cities.get('Tx','Does Not Exist')
print("The city for the state 'TX' is:%s" %city)
输出结果:

----------
NY state has: New York
OR state has: Portland
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
Oregon is abbreviated OR.
Florida is abbreviated FL.
California is abbreviated CA.
New York is abbreviated NY.
Michigan is abbreviated MI.
----------
CA has the city San Francisco.
MI has the city Detroit.
FL has the city Jacksonville.
NY has the city New York.
OR has the city Portland.
----------
Oregon state is abbreviated OR and has city Portland
Florida state is abbreviated FL and has city Jacksonville
California state is abbreviated CA and has city San Francisco
New York state is abbreviated NY and has city New York
Michigan state is abbreviated MI and has city Detroit
----------
Sorry,no Texas.
The city for the state 'TX' is:Does Not Exist

对于以上代码我们可以知道:

字典是可以直接添加一组元素的。

设某字典变量为a={ },那么:

a['a']='aa'

print(a)

输出结果是{'a': 'aa'}。

需要知道的两个概念:

①cities.items()

我们在讲出答案之前,不妨动一动脑筋自行分析一下items()的作用。

这个items()用于for in循环里面,我们知道,这个循环就是针对列表里的元组给便利出来。

那么items()的作用就很清晰了:

将字典以列表的形式返回可以遍历的元组数组。

a={'a':'aa','b':'bb','c':"cc"}
print(a)
b=a.items()
print(b)

输出结果:

{'a': 'aa', 'b': 'bb', 'c': 'cc'}
dict_items([('a', 'aa'), ('b', 'bb'), ('c', 'cc')])

看见了吗?

第二个输出结果括号内的内容是[('a', 'aa'), ('b', 'bb'), ('c', 'cc')],此时字典已经转换成了列表的形式,里面的key:value也转换成了元组的形式。

②cities.get()

我们先来看一下get()的公式用法:

dict.get(key, default=None)
key:字典中要查找的键。
default:如果此键不存在,则返回default的值,其中None为默认值。

看到以上的解释,想必大家也会恍然大悟。我们再来看看文中的代码:

state=states.get('Texas',None)

if not state:
print("Sorry,no Texas.")

在state中,'Texas'不存在,则返回None的值,然后满足if的条件,则打印出“Sorry,no Texas.”

好了,关于列表和字典,我们就复习到这儿,要时刻明确清楚列表和字典的基本概念,对于今后的编程中是有莫大的益处的。

接下来,我们进入一个新的阶段:模块、类和对象。

Python是一种面向对象编程语言,也就是OOP。

里边有一种叫做类(class)的结构,通过它可以做很多的事情,构造软件。

模块

模块的概念,大家应该已经清楚了,最经典的就是:

from sys import argv

我在博客中对这一句的解释就是,从sys功能包中提取argv功能,这是为了方便大家理解。

现在标准的解释应该是:从sys模块中导入argv参数列表。

模块就是提供函数和许多变量来处理python代码。

可以当作一个特殊的字典,通过它们可以存储一些Python功能和Python代码。

类其实和模块差不多,也是一个容器,你可以把一组函数和数据放到这个一个容器中,然后用'.'操作符来访问它们。

现在我要创建一个学生类:

class Student(object):

    def __init__(self,name,age):

        self.name=name

        self.age=age

这样,我就成功创建了一个学生类,这个类里面有学生的名字信息和年龄信息。

__init__()函数想必大家已经很熟悉了,干脆点说,这是创建一个有效类时,必须含有的一个函数。

这个__init__()函数将直接收集从类里得来数据进行处理。

对象

我会很直接明了地给你解释对象的意义,我们知道,对象有一个很高深的概念叫法,就是实例化。

意思就是一个创建,当你将一个类“实例化”后,你就得到了一个对象(object)。

我来用白话解释一下:

我在上面创建了一个学生类,是不?现在,我要在这个学生类导入一个学生的信息,这是一个18岁的huangpaopao同学。

于是就会有student1=Student('huangpaopao',18)

这样,我们把这个学生的信息存储到了变量student1中,这个变量就是一个实例化后的对象。

也就是说,对象相当于迷你导入。对象是类里面的一个实例。

现在,我放一段歌词的类代码:

class Song(object):

    def __init__(self,lyrics): #__init__shi与类联系的定义函数
        self.lyrics=lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)

happy_birthday=Song(["Happy birthday to you",
                                      "I don't want to get sued",
                                      "So I'll stop right there"])

bulls_on_parade=Song(["They rally around the family",
                                       "With pockets full of shells"])

happy_birthday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

输出结果:

Happy birthday to you
I don't want to get sued
So I'll stop right there
They rally around the family
With pockets full of shells

是否能看懂这段歌词的类代码?首先定义两个歌词变量,导入两次歌词类,使这两个歌词变量成为两个实例化后的对象。

然后再将这两个对象进行唱歌函数处理,使用'.'操作符。

原文地址:https://www.cnblogs.com/Masterpaopao/p/10105417.html