python学习初步
只给自己记录比较不容易记住的
1.切片
索引用于获得单个字符,切片 让你获得一个子字符串:
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
a.字符串从游标0开始(包括0),到2(不包括)的取值
b.字符串从游标2开始(包括2),到5(不包括)的取值
注意,包含起始的字符,不包含末尾的字符。这使得 s[:i] + s[i:] 永远等于 s
>>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python'
切片的索引有非常有用的默认值;省略的第一个索引默认为零,省略的第二个索引默认为切片的字符串的大小。
2.注意点:Python字符串不可以被更改 — 它们是不可变的 。因此,赋值给字符串索引的位置会导致错误: 这里与java不同
>>> word[0] = 'J' ... TypeError: 'str' object does not support item assignment >>> word[2:] = 'py' ... TypeError: 'str' object does not support item assignment
需要一个新的字符串只能新建:
>>> 'J' + word[1:] 'Jython' >>> word[:2] + 'py' 'Pypy'
3.列表list 重点:列表是 可变的,它允许修改元素
注意点:a.列表的元素不必是同一类型 ,如 s = [1,2,'aa']
b.所有的切片操作都会返回一个包含请求的元素的新列表。这意味着下面的切片操作返回列表一个新的(浅)拷贝副本:
>>> squares = [1, 4, 9, 16, 25] >>> squares[:] [1, 4, 9, 16, 25]
c.列表也支持连接这样的操作:
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
d.列表的方法
append
e.可以对切片赋值,此操作可以改变列表的尺寸,或清空它:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> # replace some values >>> letters[2:5] = ['C', 'D', 'E'] #这样居然就改变了列表 >>> letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] >>> # now remove them >>> letters[2:5] = [] >>> letters ['a', 'b', 'f', 'g'] >>> # clear the list by replacing all the elements with an empty list >>> letters[:] = [] >>> letters []
f.允许嵌套列表(创建一个包含其它列表的列表),例如:
>>> a = ['a', 'b', 'c'] >>> n = [1, 2, 3] >>> x = [a, n] >>> x [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b'
4.print用法
用,隔开就可以连接赋值对象 pint(x,y)
>>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536
用end=','防止换行 print(b, end=',')
>>> a, b = 0, 1 >>> while b < 1000: ... print(b, end=',') ... a, b = b, a+b ... 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
5.假如需要在循环中修改序列的时候,因为修改后,序列的大小一直在改变,所以会死循环,所以需要用到切片做一个浅复制
>>> words = ['cat', 'window', 'defenestrate'] >>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words
['defenestrate', 'cat', 'window', 'defenestrate']
结合range()函数得到java中for(int i=0;i<5;i++)效果
>>> for i in range(5): ... print(i) ... 0 1 2 3 4
>>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print(i, a[i]) ... 0 Mary 1 had 2 a 3 little 4 lamb
6.关于range函数
range(0, 10, 3) 0, 3, 6, 9
表示取[0,10)之间的数,且以3步进
如果你只是打印一个序列的话会发生奇怪的事情:
>>> print(range(10)) range(0, 10)
在不同方面 range() 函数返回的对象表现为它是一个列表,但事实上它并不是。当你迭代它时,它是一个能够像期望的序列返回连续项的对象;但为了节省空间,它并不真正构造列表。
可以用list
>>> list(range(5)) [0, 1, 2, 3, 4]
list() 函数是另外一个( 迭代器 ),它从可迭代(对象)中创建列表:
7.循环可以有一个 else 子句;它在循环迭代完整个列表(对于 for )或执行条件为 false (对于 while )时执行,但循环被 break 中止的情况下不会执行。以下搜索素数的示例程序演示了这个子句:
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
这个例子中,当n=4时候,在内循环中由于当x=2时候,break,跳出了内循环,导致内循环的else也没有被执行
8.pass语句
pass 语句什么也不做。它用于那些语法上必须要有什么语句,但程序什么也不做的场合,例如:
>>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ...
>>> class MyEmptyClass:
... pass
...
创建结构最小的类
另一方面,pass 可以在创建新代码时用来做函数或控制体的占位符。可以让你在更抽象的级别上思考。pass 可以默默的被忽视:
>>> def initlog(*args): ... pass # Remember to implement this! ...
9.函数
可变的参数
def write_multiple_items(file, separator, *args): file.write(separator.join(args))
参数列表的分拆
另有一种相反的情况: 当你要传递的参数已经是一个列表,但要调用的函数却接受分开一个个的参数值。这时候你要把已有的列表拆开来。例如内建函数 range() 需要要独立的 start,stop 参数。你可以在调用函数时加一个 * 操作符来自动把参数列表拆开:
>>> def parrot(voltage, state='a stiff', action='voom'): ... print("-- This parrot wouldn't", action, end=' ') ... print("if you put", voltage, "volts through it.", end=' ') ... print("E's", state, "!") ... >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
10.lambda形式:创建短小的匿名函数
通过 lambda 关键字,可以创建短小的匿名函数。这里有一个函数返回它的两个参数的和: lambda a, b: a+b。 Lambda 形式可以用于任何需要的函数对象。出于语法限制,它们只能有一个单独的表达式。语义上讲,它们只是普通函数定义中的一个语法技巧。类似于嵌套函数定义,lambda 形式可以从外部作用域引用变量:
>>> def make_incrementor(n): ... return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43
f就是这个返回的lambda函数
上面的示例使用 lambda 表达式返回一个函数。另一个用途是将一个小函数作为参数传递: 将pairs序列中的每个序列中第一个序列,作为键来排序
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] >>> pairs.sort(key=lambda pair: pair[1]) >>> pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
函数注解 依然不太清楚
注解是以字典形式存储在函数的 __annotations__ 属性中,对函数的其它部分没有任何影响。参数注解(Parameter annotations)是定义在参数名称的冒号后面,紧随着一个用来表示注解的值得表达式。返回注释(Return annotations)是定义在一个 -> 后面,紧随着一个表达式,在冒号与 ->之间。下面的示例包含一个位置参数,一个关键字参数,和没有意义的返回值注释:
>>> def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here": ... print("Annotations:", f.__annotations__) ... print("Arguments:", ham, eggs) ... >>> f('wonderful') Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42} Arguments: wonderful spam
浙公网安备 33010602011771号