在Python 中有四种内建的数据结构—— 列表、元组、字典和集合。

列表

list 是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项
目。

列表中的项目应该包括在方括号中,这样Python 就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。由于你可以增加或删除项目,我们说列表是可变的数据类型,即这种类型是可以被改变的。

shoplist = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shoplist), 'items to purchase.')
print('These items are:', end=' ')

for item in shoplist:
    print(item, end=' ')

print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)

print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list 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 shopping list is now', shoplist)

元组

元组用来将多样的对象集合到一起。元组和列表十分类似,只不过元组和字符串
一样是不可变的即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。

元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用
的元组的值不会改变。

zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))

new_zoo = ('monkey', 'camel', zoo)
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',len(new_zoo)-1+len(new_zoo[2]))

字典

字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。

键值对在字典中以这样的方式标记:d = key1 : value1, key2 : value2 。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。

字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。

字典是dict 类的实例/对象。

ab = { 'Swaroop' : 'swaroop@swaroopch.com',
    'Larry' : 'larry@wall.org',
    'Matsumoto' : 'matz@ruby-lang.org',
    'Spammer' : 'spammer@hotmail.com'
    }

print("Swaroop's address is", ab['Swaroop'])

# Deleting a key-value pair
del ab['Spammer']

print('\nThere are {0} contacts in the address book\n'.format(len(ab)))

for name, address in ab.items():
    print('Contact {0} at {1}'.format(name, address))

ab['Guido'] = 'guido@python.org'
if 'Guido' in ab: # OR ab.has_key('Guido')
    print("\nGuido's address is", ab['Guido'])

我们可以使用del 语句来删除键/值对。

序列

列表、元组和字符串都是序列

序列的主要特点是索成员检验(例如,在和不在表达式中)和索引操作符,索引操作符让我们可以直接从序列中抓取一个特定项目。

上面提到的三种类型的序列—— 列表、元组和字符串,也有切片操作,切片操作让我们取出序列的薄片,例如序列的部分。

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[:])

# Slicing on a string
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[:])

索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。因此,shoplist[-1] 表示序列的最后一个元素而shoplist[-2] 抓取序列的倒数第二个项目。

切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的。

切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python 就从序列首开始。如果没有指定第二个数,则Python 会停止在序列尾。注意,返回的序列从开始位置开始,刚好在结束位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。

这样,shoplist[1:3] 返回从位置1 开始,包括位置2,但是停止在位置3 的一个序列切片,因此返回一个含有两个项目的切片。类似地,shoplist[:] 返回整个序列的拷贝。

你可以用负数做切片。负数用在从序列尾开始计算的位置。例如,shoplist[:-1] 会返回除了最后一个项目外包含所有项目的序列切片。

你也可以给切片规定第三个参数,就是切片的步长(默认步长是1)。

集合

集合是没有顺序的简单对象的聚集。当在聚集中一个对象的存在比其顺序或者出现的次数重要时使用集合。

使用集合,可以检查是否是成员,是否是另一个集合的子集,得到两个集合的交集等等。

>>> bri = set(['brazil', 'russia', 'india'])
>>> 'india' in bri
True
>>> 'usa' in bri
False
>>> bric = bri.copy()
>>> bric.add('china')
>>> bric.issuperset(bri)
True
>>> bri.remove('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}

引用

当你创建一个对象并给它赋一个变量的时候,这个变量仅仅引用那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。

print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the
same object!

del shoplist[0] # I purchased the first item, so I remove it from
the list

print('shoplist is', shoplist)
print('mylist is', mylist)
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object

print('Copy by making a full slice')
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item

print('shoplist is', shoplist)
print('mylist is', mylist)