Python入门语法要点

来源:互联网 发布:易宠软件 登录 编辑:程序博客网 时间:2024/05/29 17:11

Python入门语法要点


首先要说一下博主是有一丢丢C语言基础的,所以本博审略了一些基本的内容o(^▽^)o,若有不对的地方,还请大家批评指正!共同进步!

dict

访问dict

dict就是存储Key-Value键值对的数据结构啦,举个例子:

d = {        'Adam':180,        'Bart':160,        'Lisa':155}

这就是一个存储{人物及其身高}的dict。key就是’Adam’列,value就是180列。我们必须通过key来访问dict的value,如果没有找到对应的key,则报错:KeyError。

解决KeyError问题有两个方法:
1.

if 'Paul' in d:      print d['Paul']
 即先判断该key是否存在。

2.

d.get('Paul')
使用dict自带的get方法。若key不存在,则返回none

输出dict内容:
1.

for (key,value) in d.items():    print("%s : %s" %(key,value))

2.

print 'Adam : ' + str(d.get('Adam'))

注意:因为使用“+”链接字符串,所以此处要使用str来将其转换为字符串!
3.

print 'Adam',d.get('Adam')

dict特点

  • 查找速度快 dict的查找速度和包含元素个数无关。
  • 占用内存大
  • Key不能重复
  • key-value存储没有顺序
  • 作为key的元素必须不可变。而value的元素没有要求。
    Python的基本类型都是不可变的(例如:字符串、整数、浮点数),而list是可变的。

更新dict

dict是可变的,我们可以随时向其添加key-value。

d['xixi'] = 165

则会新添 {…’xixi’ : 165…}这个数据项,如果指定的key已经存在,则更新对应的value。

遍历dict

for name in d:
print name+”:”+str(d.get(name))


set

顾名思义,set是集合,包含一系列不重复且无序的元素。

创建set

>>>s = set(['A','B','C'])

查看set

>>>print sset(['A','B','C'])

set自动去重

>>>s = set(['A','B','C','C'])>>>print sset(['A','B','C'])>>>len(s)3

访问set

因为set是集合呀,所以我们不能直接访问它,只能通过判断一个元素是否存在于这个集合里。这就要使用到——in

>>>'Paul' in sTrue

set的特点

  • 判断元素是否存在速度很快
  • 对象必须是不可变的。这一点和dict很像啊o( ̄▽ ̄)ブ
  • 存储的元素是无序的

遍历set

>>>for name in s:      print name

不赘述啦,和dict一样~

更新set
1. 添加新元素:

s.add(1)
  1. 删除旧元素:
s.remove(1)

如果删除不存在的元素,则会报错:KeyError。所以,童鞋们最好在删除之前加一个判断

if name in s:...

函数

说到函数大家一定不陌生,编写函数要具备哪种素质呢——那就是抽象能力!此处不再赘述。

Python内置了很多函数,供大家直接调用。比如求绝对值的函数abs,发一个Python的官方网站查看文档:
[http://docs.python.org/2/library/functions.html#abs]

也可以在命令行通过help(abs)查看abs函数的帮助信息。

>>>abs(-20)20

调用函数时,若传入的参数数量不对,会报错:TypeError;若传入的参数数量对,但类型不对,也会报错:TypeError。

编写函数

在Python中,定义一个函数使用def关键字,依次写入 函数名、括号、参数、冒号

def my_func(x):        if x >= 0:            return x        else:            return -x

注意:如果没有return语句,函数执行完毕后会默认返回None。

返回多值

Python可以返回多值吗?是,也不是( •̀ ω •́ )y
来看看,当我们编写如下的代码段时:

import mathdef move(x,y,step,angel):    nx = x + step * math.cos(angle)    ny = y - step * math.sin(angle)    return nx, ny

看似我们可以得到两个返回值。但其实这是一种假象,Python函数返回的仍然是单一值:

>>>r = move (100, 100, 60, math.pi/6)>>>print r(151.96152422706632,70.0)

所以Python是用tuple来实现多值返回的!

递归函数

递归函数就不在这里赘述了,需要注意的是防止栈溢出,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。

默认参数

定义函数的时候,可以有默认参数,用来简化调用
比如定义一个计算N次方的函数:

def power(x, n):    s = 1    while n > 0:        n = n -1        s = s * x    return s

我们发现计算平方的次数最多,那么我们可以将n默认为2:

def power(x, n=2):    s = 1    while n > 0:        n = n -1        s = s * x    return s

注意:默认参数只能定义在必须参数的后面!

可变参数

如果想让一个函数能接受任意个参数,我们就可以定义一个可变参数:

def fn(*args):    print args

可变参数是怎么实现的呢?其实还是tuple。Python解释器会把传入的一组参数组装成一个tuple传递给可变参数。可变参数的目的也是为了简化调用。


切片

切片(Slice),顾名思义,就是切取list的一部分信息。
比如取一个list的前三个元素:注意噢,这里是0开头,3结尾!

>>>L[0:3]

如果第一个索引是0,还可以省略:

>>>L[:3]

只用:,表示从头取到尾:

>>>L[:]

切片操作还可以指定三个参数:
L[ : : 2]
第三个参数表示每N个取一个,上面的代码表示每两个元素取出一个,即每隔一个取一个。

当然,切片操作不局限于list,也可以使用与tuple!

倒序切片

和普通切片同理,L[-2:]表示从倒数第二个元素开始,一直取到最后一个元素。
倒序切片包含起始索引,不包含结束索引。

对字符串切片

>>>'ABCDEFG'[:3]'ABC'

小练习

>>>L = range(1,101)[1,2,3,...,100]

1)前十个数:

L[0:10]

从第一个数开始,取到第十个数。

2)3的倍数:

L[2::3]

从第三个数开始,取到最后,每隔2个数取一次。

3)不大于50的5的倍数:

L[4:51:5]

从第五个数开始,取到第51个数,每隔4个数取一次。

**总结:
[0::]第一个数为0 ,表示从第一个数开始。
[::n]第三个数为n,表示每隔n-1个数取一次。**


迭代

集合

1.有序集合:list,tuple,str,unicode
2.无序集合:set
3.无序集合并且具有key-value对:dict

索引迭代

如果我们想要通过迭代取得元素的索引呢?答案是使用——enumerate()函数

>>>L = ['Adam','Lisa','Bart','Paul']>>>for index , name in enumerate(L):. . .           print index,'-',name. . .0 - Adam1 - Lisa2 - Bart3 - Paul

使用enumerate()函数,可以在for循环中同时绑定索引index和元素name。
具体实现的过程,对,肯定猜到了,也是将其转换为了tuple类型。这里就不赘述啦。

迭代dict的value

我们已经知道了dict对象可以使用for循环迭代,每次拿到dict的一个key。
如果我们迭代dict对象的value,就可以使用——values()方法!

d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }print d.values()# [85, 95, 59]for v in d.values():    print v# 85# 95# 59

dict除了values()方法外,还有一个 itervalues() 方法,用 itervalues() 方法替代 values() 方法,迭代效果完全一样。

d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }print d.itervalues()# <dictionary-valueiterator object at 0x106adbb50>for v in d.itervalues():    print v# 85# 95# 59

那这两个方法有何不同之处呢?

  1. values() 方法实际上把一个 dict 转换成了包含 value 的list。

  2. 但是 itervalues() 方法不会转换,它会在迭代过程中依次从 dict 中取出 value,所以 itervalues() 方法比 values() 方法节省了生成 list 所需的内存。

  3. 打印 itervalues() 发现它返回一个 对象,这说明在Python中,for 循环可作用的迭代对象远不止 list,tuple,str,unicode,dict等,任何可迭代对象都可以作用于for循环,而内部如何迭代我们通常并不用关心。

如果一个对象说自己可迭代,那我们就直接用 for 循环去迭代它,可见,迭代是一种抽象的数据操作,它不对迭代对象内部的数据有任何要求。

迭代dict的key和value

我们先看看dict对象的items()方法返回值:

d = {'Adam':95,'Lisa':85,'Bart':59}print d.items()[('Lisa',85),('Adam',95),('Bart',59)]

可见items()方法把dict对象转换成了包含tuple的list,我们对这个list进行迭代,同时获得key和value:

for key , value in d.items():        print key , ':' , value

和 values() 有一个 itervalues() 类似, items() 也有一个对应的 iteritems(),iteritems() 不把dict转换成list,而是在迭代过程中不断给出 tuple,所以, iteritems() 不占用额外的内存。

列表

生成列表

>>>range(1,11)[1,2,3,4,5,6,7,8,9,10]
>>>L=[]>>>for x in range(1,11):. . .           L.append(x*x). . . >>>L[1,4,9,16,25,36,49,64,81,100]

上面的代码同下:

>>>[x * x for x in range(1,11)][1,4,9,16,25,36,49,64,81,100]

条件过滤

列表生成式的for循环后面还可以加上if判断。

>>>[x * x for x in range(1,11)][1,4,9,16,25,36,49,64,81,100]

如果我们只想要偶数的平方,不改动 range()的情况下,可以加上 if 来筛选:

>>> [x * x for x in range(1, 11) if x % 2 == 0][4, 16, 36, 64, 100]

有了 if 条件,只有 if 判断为 True 的时候,才把循环的当前元素添加到列表中。

多层表达式

for循环可以嵌套,因此,在列表生成式中,也可以用多层 for 循环来生成列表。

对于字符串 ‘ABC’ 和 ‘123’,可以使用两层循环,生成全排列:

>>> [m + n for m in 'ABC' for n in '123']['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']

Mark
zip: https://docs.python.org/3/library/functions.html#zip

unpacking argument lists : https://docs.python.org/3/tutorial/controlflow.html#tut-unpacking-arguments

A tuple consists of a number of values separated by commas,Tuples are immutable

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective

For example:

>

empty = ()
singleton = ‘hello’, # <– note trailing comma
len(empty)
0
len(singleton)
1
singleton
(‘hello’,)

sequence unpacking???

questions = [‘name’, ‘quest’, ‘favorite color’]
answers = [‘lancelot’, ‘the holy grail’, ‘blue’]
for q, a in zip(questions, answers):
… print(‘What is your {0}? It is {1}.’.format(q, a))

What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined.

string1, string2, string3 = ”, ‘Trondheim’, ‘Hammer Dance’
non_null = string1 or string2 or string3
non_null
‘Trondheim’

Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

6.1.1. Executing modules as scripts
When you run a Python module with

python fibo.py
the code in the module will be executed, just as if you imported it, but with the name set to “main“. That means that by adding this code at the end of your module:

if name == “main“:
import sys
fib(int(sys.argv[1]))
you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

$ python fibo.py 50
1 1 2 3 5 8 13 21 34
If the module is imported, the code is not run:

>

import fibo

This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).

for x in range(1, 11):
… print(repr(x).rjust(2), repr(x*x).rjust(3), end=’ ‘)
… # Note use of ‘end’ on previous line
… print(repr(x*x*x).rjust(4))

1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

for x in range(1, 11):
… print(‘{0:2d} {1:3d} {2:4d}’.format(x, x*x, x*x*x))

1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

print(‘{0} and {1}’.format(‘spam’, ‘eggs’))
spam and eggs
print(‘{1} and {0}’.format(‘spam’, ‘eggs’))
eggs and spam

range()和xrange():

在Python2中
1.range()返回一个list对象,xrange()返回一个xrange object 对象,且这个对象是iterable的;
2.xrange()占用的空间更小,其只在需要的时候生成当前的一个元素,而range()是在一开始就生成整个list;
3.都用于for循环

在Python3中
1.range()被移除,xrange()更名为range();
2.在range object 中新增了属性:count、start、stop、step、index,且支持slicing
3.The advantage of the range type over a regular list or tuple is that a range object will always take the same(small) amount of memory,no matter the size of range it represents(as it only stores the start,stop and step values,calculating individual items and subranges as needed)
基于list或者tuple的range类型的优点在于:这个range类型将会花费一样的内存空间,而与你的range大小无关。

Private Variables
python用下划线作为变量前缀和后缀制定特殊变量
_xxx : 不能用‘form module import*’导入,叫做保护变量,只有类对象和子类对象自己能访问到这些变量
__xxx: 类中的私有变量,只有类对象自己能访问,连子类对象也不能访问
xx: 系统定义的鸣奏

会有不定期更新哦~

2 0
原创粉丝点击