'doesn\'t' 单引号,需要转义
"doesn't" 双引号,不需要转义
不想转义,行首使用r
print(r'C:\some\name')
打印多行,使用三引号"""…."""
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
使用+进行字符串连接
使用[id1:id2]进行索引
List[]
list是可变类型,可对自身进行修改,[,,,]
使用.append()添加
可以进行嵌套
If-elif-else
for i in indexArray
Range()
Def f()定义函数,可以指定默认参数
参数说明:
*name 参数列表
**name map
*name必须在**name前出现
可变参数:
def concat(*args, sep="/"):
... return sep.join(args)
从*-operato中解析参数,如
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
类似,字典可以使用**-operator进行解析
>>> 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 !
lambda:定义匿名函数(表达式)
g = lambda x:x+1
list.append(x)
list.extend(iterable)
list.insert(i, x)
list.remove(x)
list.pop([i])
list.clear()
list.index(x[, start[, end]])
list.count(x)
list.sort(key=None, reverse=False)
list.reverse()
list.copy()
Using Lists as Stacks :append,pop
Using Lists as Queues :append,deque,
from collections import deque
list推导:
squares = [x**2 for x in range(10)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
Del 删除
Tuples and Sequences()
元组:类似于元胞数组,非可变(list是可变的)
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
Sets{}
Sets:不包含重复内容,可用于集合计算,如 a-b,a+b,a|b
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
a = set('abracadabra')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
Dictionaries{}
通过key进行索引,用于非可变数据类型
tel = {'jack': 4098, 'sape': 4139}
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
dict(sape=4139, guido=4127, jack=4098)
Looping Techniques
.items()
zip()
是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)。
Comparing Sequences and Other Types
本文深入探讨Python的字符串处理技巧,包括转义字符、多行打印与字符串连接。讲解了列表、元组、集合与字典的使用方法,以及高级特性如列表推导、lambda表达式和可变参数函数。同时,介绍了Python中的循环技巧和序列比较。
407

被折叠的 条评论
为什么被折叠?



