python basics

本文深入探讨Python的字符串处理技巧,包括转义字符、多行打印与字符串连接。讲解了列表、元组、集合与字典的使用方法,以及高级特性如列表推导、lambda表达式和可变参数函数。同时,介绍了Python中的循环技巧和序列比较。

'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(ix)

list.remove(x)

list.pop([i])

list.clear()

list.index(x[start[end]])

list.count(x)

list.sort(key=Nonereverse=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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值