数据结构(Data Structures)基本上人如其名,他们是一种结构,能够将一些数据聚合在一起。
Python内置四种数据结构

  • 列表(list)
  • 元组(tuple)
  • 字典(dictionary)
  • 集合(set)

我们要学会理解和运用它们,让我们的变成之路更简单。

列表

有序的集合,可以添加、移除、搜索列表中的项目。可变的(Mutable)

插入一段类和对象的介绍

列表是使用对象与类的实例。当我们启用一个变量 i 并将整数 5 赋值给它时,你可以认为这是在创建一个 int 类(即类型)之下的对象(即实例) i 。

一个类可以带有方法(Method)
一个类同样可以有字段(Field)

shoplist = ['apple', 'mango', 'carrot', 'banana']
print('These items are:', end=' ')
for item in shoplist:
    print(item,end=' ')
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shoppinglist is now',shoplist)

print('I will sort my shoplist now')
shoplist.sort()
print('Sorted shoplist is',shoplist)

print('The first item I will buy is',shoplist[0])

olditem=shoplist[0]
del shoplist[0]
print('I bought the',olditem)
print('My shop list is now',shoplist)

运行结果:

These items are: apple mango carrot banana 
I also have to buy rice.
My shoppinglist is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my shoplist now
Sorted shoplist is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shop list is now ['banana', 'carrot', 'mango', 'rice']

在这里要注意在调用 print 函数时我们使用 end 参数,这样就能通过一个空格来结束输出工作,而不是通常的换行。

注意:我们列表的 sort 方法对列表进行排序。在这里要着重理解到这一方法影响到的是列表本身,而不会返回一个修改过的列表——这与修改字符串的方式并不相同。同时,这也是我们所说的,列表是可变的(Mutable)而字符串是不可变的(Immutable)。

元组

我们可把他近似地看成列表,但是元组不能提供列表能够提供的广泛功能。元组的一大特征是类似字符串,它是不可变的,也就是说你不能编辑或更改元组。

元组通常用于保证某一语句或某一用户定义的函数可以安全地采用一组数值,意即元组内的数值不会改变。

这种使用方括号的形式被称作索引(Indexing)运算符。我们通过指定new_zoo[2] 来指定 new_zoo 中的第三个项目,我们也可以通过指定 new_zoo[2][2] 来指定new_zoo 元组中的第三个项目中的第三个项目

包含 0 或 1 个项目的元组
一个空的元组由一对圆括号构成,就像 myempty = () 这样。然而,一个只拥有一个项目的元组并不像这样简单。你必须在第一个(也是唯一一个)项目的后面加上一个逗号来指定它,如此一来 Python 才可以识别出在这个表达式想表达的究竟是一个元组还是只是一个被括号所环绕的对象,也就是说,如果你想指定一个包含项目 2 的元组,你必须指定 singleton = (2, )

字典

顾名思义,就想查字典,或者地址簿,知道了姓名,就能查到它的更多信息比如电话号码。key-value,键值对,把他们2个联系起来。键值必须是唯一的,正如现实中两个同名的人,你没办法找出正确的信息。

另外,只能用不可变对象作为key,但是可以用可变或者不可变对象作为value。
还有,他们是字典中的key-value 是无序的。

ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
print('There are {} contacts in the address-book'.format(len(ab)))
del ab['Spammer']
print('There are {} contacts in the address-book'.format(len(ab)))
for name,address in ab.items():
    print('Contact {} at {}'.format(name,address))
ab['Guido']='guido@python.org'
if 'Guido' in ab:
    print('Guido\'s address is',ab['Guido'])

运行结果:

There are 4 contacts in the address-book
There are 3 contacts in the address-book
Contact Swaroop at swaroop@swaroopch.com
Contact Larry at larry@wall.org
Contact Matsumoto at matz@ruby-lang.org
Guido's address is guido@python.org

序列

列表、元组和字符串可以看作序列(Sequence)的某种表现形式,可是究竟什么是序列,它又有什么特别之处?

序列的主要功能是资格测试(Membership Test)(也就是 in 与 not in 表达式)和索引操作(Indexing Operations),它们能够允许我们直接获取序列中的特定项目。

上面提到的列表、元组、字符串3种序列都有一种切片(Slicing)运算,它能允许我们序列中某块切片-也就是序列中的一部分。

shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
# Indexing or 'Subscription' operation #
# 索引或“下标(Subscription)”操作符 #
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Character 0 is', name[0])
# Slicing on a list #
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])
# 从某一字符串中切片 #
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])

运算结果:

Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Character 0 is s
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop

你同样可以在切片操作中提供第三个参数,这一参数将被视为切片的步长(Step)(在默认情况下,步长大小为 1):

>>> shoplist = ['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::1]
['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::2]
['apple', 'carrot']
>>> shoplist[::3]
['apple', 'banana']
>>> shoplist[::-1]
['banana', 'carrot', 'mango', 'apple']

你会注意到当步长为 2 时,我们得到的是第 0、2、4…… 位项目。当步长为 3 时,我们得到的是第 0、3……位项目。

序列的一大优点在于你可以使用同样的方式访问元组、列表与字符串。


list

classmates=[‘mike’,’lucy’,’jim’]
有序的集合,可以随时添加删除其中的元素
classmates[-1]
calssmates[0]

tuple

classmatea=(‘mike’,’lucy’,’jim’)
有序的集合,不能添加删除,一旦初始化就不能修改

dict

d={‘mike’:95,’lucy’:88,’jim’:60}
字典,使用键-值(key-value)储存,极快的查找速度
d[‘mike’]

set

s=set([1,2,3])
set 和 dic 类似,也是一组key的集合,但是不储存value。由于key不能重复,所以set中没有重复的key
要创建一个set,要提供一个list作为输入集合。