Python基础之内置类型与数据结构

Data Structures

数值Numbers

简单的数值计算,计算器功能
运算符

+  -  *  /
//     #保留整数部分
%    #取余数
**     #power

字符串Strings

  1. 单引号和双引号,不冲突原则
  2. 单引号中\nprint时要换行,使用r前缀避免解释转意字符
  3. +,*操作
    3 * 'un' + 'ium' => unununium
    'Py' 'thon' => Python #这种操作只能简单连接,不能复合操作('un' * 3) 'ium'
  4. Strings can be indexed (subscripted)
word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
  1. 能索引就意味着能切片
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
  1. 看一看索引号,可以这样认为:正索引从0开始左闭右开,负索引从-1开始全闭
+---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
  1. 不可通过索引改变string的元素,Python strings cannot be changed — they are immutable
  2. len() returns the length of a string

列表Lists

  1. 通过[]定义列表squares = [1, 4, 9, 16, 25]
  2. 和String一样List也是内置的sequence类型所以能够使用同样的索引和切片方法
  3. Lists也支持合并+操作
  4. Lists是mutable的,
  • 使用赋值=操作来改变元素值cubes[3] = 64或者letters[2:5] = ['C', 'D', 'E']
  • 在末尾加入新项cubes.append(216)
  1. 同样可以使用len()返回长度
  2. 支持嵌套使用,It is possible to nest lists (create lists containing other lists)。
>>> 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'
  1. 下面总结一下Lists的操作方法
  • list.append(x)**:末尾增一项,这一项可以是各种对象。Add an item to the end of the list; equivalent to a[len(a):] = [x]

  • list.extend(L)**:先展开所增对象,然后在末尾一一增项,Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L

  • list.insert(i, x)**:在i位置插入一项x。Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x)

  • list.remove(x)**:删除值为x的索引值最小项。Remove the first item from the list whose value is x. It is an error if there is no such item.

  • list.pop([i])**:删除并返回给定位置i的项,如果使用pop()则是删除最后一项并返回其值。Remove the item at the given position in the list, and return it. If no index is specified, a.pop()removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

  • list.index(x)**:返回值为x的第一项索引号。Return the index in the list of the first item whose value is x. It is an error if there is no such item.

  • list.count(x)**:返回x出现的次数。Return the number of times x appears in the list.

  • list.sort(cmp=None, key=None, reverse=False)**: 排序。Sort the items of the list in place (the arguments can be used for sort customization.

  • list.reverse():倒转Lists。Reverse the elements of the list, in place.

  1. 通过上面方法的总结,通常以如下几种方式使用List
  • Using Lists as Stacks (“last-in, first-out”):append and pop method,
  • Using Lists as Queues (“first-in, first-out”): using collections.deque
from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves'Eric'
>>> queue.popleft() # The second to arrive now leaves'John'
>>> queue # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])

Functional Programming Tools: 函数式编程工具

有三个内置函数在Lists的使用上非常方便:

  1. filer(function, sequence): 返回一个sequence,返回序列对原序列的筛选,筛选方法是function。返回的序列与原序列类型相同,可以使用这个方法筛选数据。这里作为参数的function定义有一定要求,fucntion要有一个参数,并且其返回值只能是0或1,所以这个函数逻辑性的过滤函数
>>> def f(x): return x % 3 == 0 or x % 5 == 0
...
>>> filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
  1. map(function,sequence,seq...): 返回一个sequence,返回序列各个项是function作用到原序列各个项获得的结果。这里的作用函数特点是,参数个数要与map的序列个数一致,并且各个序列的长度要一致。function返回与这些参数相关的值。这是一个典型的映射操作(map)。
  • 单序列映射
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
  • 多序列映射
def func2(x,y,z):  return x+y*z
a = range(7);  b = range(7,14)
dd = map(func2,a,b,a)
//result:[0, 9, 20, 33, 48, 65, 84]

map()的原理可以用下图表示:


map(f, seq, seq, ...)
  1. reduce(function,seq) : reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)。注意,funciton的参数只能有两个。
    这里列举几个例子体会一下reduce()的使用:
  • 求和
>>> def add(x, y)
:...  return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
  • 把序列[1, 3, 5, 7, 9]变换成整数13579
def func3(x,y):
        return 10*x+y
ff = reduce(func3,[0,1,2,3,4])
print(ff)
#result: 1234
  • str转换为int
def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2int(s): return reduce(lambda x,y: x*10+y, map(char2num, s))

List Comprehensions列表生成式

  1. range
 >>> range(1, 11)  
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1. for...in...
>>> L = []
>>> for x in range(1, 11):
...  L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  1. 列表生成式(一层循环)
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

当然,还可以用lambda&map来写

map(lambda x: x*x, range(1,11))

但是,这样表达没有列表生成器简明易读(it’s more concise and readable)

  1. 列表生成式(两层循环),所得列表长度等于循环次数
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
  1. 列表生成器(增加if判断)
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Tuples and Sequences 元组和序列

A tuple consists of a number of values separated by commas. tuple通常用()表示,tuple属于immutable类型的序列,不支持赋值操作,但是它可以嵌套mutable的list类型( however it is possible to create tuples which contain mutable objects, such as lists.).

  • tuple packing: t = 12345, 54321, 'hello!'
  • tuple unpacking: x,y,z = t
  • tuple元素为异构的,通过unpack或index方式访问;sequence元素为同构的,通过iterator方式访问
  • 两种特殊的tuple
# tuple with zero or one element
>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> singleton
('hello',)
  • tuple packing and unpacking
t = 12345, 54321, 'hello!'             # packing
x, y, z = t                            # unpacking
  • 遍历list, 按索引值和value值显示, enumerate
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
  • 同时遍历两个list, zip
>>> 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))

Sets 集合

A set is an unordered collection with no duplicate elements.Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.Note: to create an empty set you have to use set(), not{},创建空set要使用set()不能用{}

  • list生成set
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
  • string生存set
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
  • 集合操作
    • a - b : 差集 in a but not in b
    • a | b : 或集 in either a or b
    • a & b : 并集 in both a and b
    • a ^ b : (a | b) - (a & b) in a or b but not both
  • set comprehensions集合生成器
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
set(['r', 'd'])
  • 添加与删除方法
    • add(key)
    • remove(key)

Dictionaries字典

  • 删除一个元素, del(dic)
  • 列出所有的key, list(dic)
  • 按value排序key, sorted(dic)
  • 判断key是否存在, key in dic
  • 遍历字典
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容