python学习笔记3

再次重申学习的是某位THU大神,网址贴下

http://nbviewer.jupyter.org/github/lijin-THU/notes-python/tree/master/

只贴了我不太熟悉的 适合有其他编程语言基础的看

Chat 4 list

列表的加法,相当于将两个列表按顺序连接

a = [1, 2, 3]
b = [3.2, 'hello']
a + b
l = [1, 2.0, 'hello']
l * 2
# 列表与整数相乘,相当于将列表重复相加

我们知道字符串是无法直接进行修改的,那么要修改其中的一个类型怎么办呢?

如果转化list的话,那就简单许多了

>>> s='abcdef'                  #原字符串
>>> s1=list(s)                  #将字符串转换为列表
>>> s1                         
['a', 'b', 'c', 'd', 'e', 'f']  #列表的每一个元素为一个字符
>>> s1[4]='E'                   #将列表中的第5个字符修改为E
>>> s1[5]='F'                   #将列表中的第5个字符修改为E
>>> s1
['a', 'b', 'c', 'd', 'E', 'F']  
>>> s=''.join(s1)               #用空串将列表中的所有字符重新连接为字符串
>>> s
'abcdEF'                        #新字符串

list当中的整段替换

a = [10, 11, 12, 13, 14]
a[1:3] = [1, 2, 3, 4]
print a

对于不连续(间隔step不为1)的片段进行修改时,两者的元素数目必须一致:

否则会报错

a = [10, 11, 12, 13, 14]
a[::2] = [1, 2, 3]
a[::2] = []
# 上面这一句 右边为空,所以无法运行

删除元素

a = [1002, 'a', 'b', 'c']
del a[0]
del a[1:]
del a[::2]

测试从属关系

a = [10, 11, 12, 13, 14]
print 10 in a
print 10 not in a
# 同样可以用于字符串
s = 'hello world'
print 'he' in s
print 'world' not in s

list.count(object) 返回元素的次数

list.index(object) 返回元素第一次

list.append(object) 将元素object添加了列表最后

list.extend(newList) 将newList添加到列表最后,这里和 list += newList 一样

l.insert(idx, ob)在索引 idx处插入 ob ,之后的元素依次后移

l.remove(ob)移除元素

l.pop(idx) 将索引处的元素删除

a = [10, 11, 12, 13, 11]
# 在索引 3 插入 'a'
a.insert(3, 'a')
print a 
a = [10, 11, 12, 13, 11]
# 移除了第一个 11
a.remove(11)
print a
a = [10, 11, 12, 13, 11]
a.pop(2)

sorted可以不影响原来的元素

a = [10, 1, 11, 13, 11, 2]
b = sorted(a)
print a
print b

除了a.reverse()的取反方法,还有如下的方式

a = [1, 2, 3, 4, 5, 6]
b = a[::-1]

介绍一个深拷贝和浅拷贝的问题,知道C++应该对这个概念很熟悉

下面这个例子应该非常明显的

b = [12, 23]
a = b
b[1] = 99
a
# 下面这个例子是所谓的深拷贝
b = [12, 23]
import copy
a = copy.copy(b)
b[1] = 99
a
# 还有一种deepCopy,是比copy更深的拷贝,对于list内部的list也是深拷贝

Chat 5 tuple and dictionary

与列表相似,元组Tuple也是个有序序列,但是元组是不可变的,用()生成。

t = (10, 11, 12, 13, 14)

一个元素的元组

a = (10,)
type(a)
# 下面这种写法其实不是元组
a = (10)
type(a)

除此之外,还有a.count(obt) a.index(obj)这种和list差不多的功能

下面稍微比较下tuple和list

测试之前我主观认为tuple的速度是比list快

%timeit可以测试一个时间

%timeit [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
%timeit (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25)
from numpy.random import rand
values = rand(10000,4)
lst = [list(row) for row in values]
tup = tuple(tuple(row) for row in values)
%timeit for row in lst: list(row)
%timeit for row in tup: tuple(row)

最后的结论是元组的生成速度会比列表快很多

下面的时候介绍下dictionary

出于hash的目的,Python中要求这些键值对的必须是不可变的,而值可以是任意的Python对象。

synonyms = {}
synonyms['mutable'] = ['changeable', 'variable', 'varying', 'fluctuating',
                       'shifting', 'inconsistent', 'unpredictable', 'inconstant',
                       'fickle', 'uneven', 'unstable', 'protean']
synonyms['immutable'] = ['fixed', 'set', 'rigid', 'inflexible', 
                         'permanent', 'established', 'carved in stone']
synonyms

dict还可以嵌套dict,如下的例子

# 定义四个字典
e1 = {'mag': 0.05, 'width': 20}
e2 = {'mag': 0.04, 'width': 25}
e3 = {'mag': 0.05, 'width': 80}
e4 = {'mag': 0.03, 'width': 30}
# 以字典作为值传入新的字典
events = {500: e1, 760: e2, 3001: e3, 4180: e4}
events

除了通常的定义方法,还可以通过dict()转化来生成字典

inventory = dict(
    [('foozelator', 123),
     ('frombicator', 18), 
     ('spatzleblock', 34), 
     ('snitzelhogen', 23)
    ])
inventory['frombicator'] += 1
# 直接更新每种键值
inventory
person = {}
person['first'] = "Jmes"
person['last'] = "Maxwell"
person['born'] = 1831
print person
person_modifications = {'first': 'James', 'middle': 'Clerk'}
person.update(person_modifications)
# 除了正常的person的表示,还可以使用

不知道某种key是否存在?可以尝试使用

a = {}
a["one"] = "this is number 1"
a["two"] = "this is number 2"
a.get("one")
a.get("three", "undefined")
# 如果没有这个key,就输出undefined

Dictionary可以使用pop删除元素,这里和list类似

细心的童鞋应该记得

list的删除是a.pop(2),删除第几个元素

dict的删除是a.pop("two"), 删除相应的键值

a.pop("two", 'not exist')
# 如果不存在就输出not exist
del a["one"]
# del和pop同样的功能

d.keys()返回一个由所有键组成的列表;

d.values()返回一个由所有值组成的列表;

d.items()返回一个由所有键值对元组组成的列表;

原文地址:https://www.cnblogs.com/Basasuya/p/8684236.html