《简明Python教程》之数据结构

Python 中有四种内置的数据结构——列表(List)、元组(Tuple)、字典(Dictionary)和集合(Set)

列表

有序项目的集合,逗号隔开,方括号括起来。
列表是使用对象与类的实例。
你可以向列表中添加任何类型的对象,包括数字,甚至是其它列表。

# This is my shopping list
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)

以上实例代码中print('These items are:', end=' ')出错,unresolved reference ‘end’。原因还未知???

元组

元组(Tuple)用于将多个对象保存到一起
近似地看作列表,但是元组不能提供列表类能够提供给你的广泛的功能。
元组的一大特征类似于字符串,它们是不可变的,也就是说,你不能编辑或更改元组。
逗号隔开,括号括起来。
方括号的形式被称作索引(Indexing)运算符
元组中所包含的元组不会失去其所拥有的身份

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

输出:

('Number of animals in the zoo is', 3)
('Number of cages in the new zoo is', 3)
('All animals in new zoo are', ('monkey', 'camel', ('python', 'elephant', 'penguin')))
('Animals brought from old zoo are', ('python', 'elephant', 'penguin'))
('Last animal brought from old zoo is', 'penguin')
('Number of animals in the new zoo is', 5)

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

字典

key – value,键值必须是唯一
冒号组对,括号分隔,花括号括起,方括号索引。

d = {key : value1 , key2 : value2}

字典中的成对的键值—值配对不会以任何方式进行排序。如果你希望为它们安排一个特别的次序,只能在使用它们之前自行进行排序

# “ab”是地址(Address)簿(Book)的缩写

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'])

 # 删除一对键值—值配对
del ab['Spammer']

print('\nThere are {} contacts in the address-book\n'.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("\nGuido's address is", ab['Guido'])

输出:

("Swaroop's address is", 'swaroop@swaroopch.com')

There are 3 contacts in the address-book

Contact Swaroop at swaroop@swaroopch.com
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
("\nGuido's address is", 'guido@python.org')

in 运算符来检查某对键值—值配对是否存在。

序列

序列的主要功能是资格测试(Membership Test)(也就是 in 与 not in 表达式)和索引操作(Indexing Operations),它们能够允许我们直接获取序列中的特定项目。
上面所提到的序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing)运算符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。

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

 # Indexing or 'Subscription' operation #
 # 索引或“下标(Subcription)”操作符 #
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')

索引操作也可以使用负数,在这种情况下,位置计数将从队列的末尾开始。因此,shoplist[-1] 指的是序列的最后一个项目,shoplist[-2] 将获取序列中倒数第二个项目。

shoplist[1:3]可选,冒号分隔,方括号括起。从位置 1 开始,包含位置 2 并在位置 3 时结束
shoplist[:-1] 强返回一组序列切片,其中不包括序列的最后一项项目,但其它所有项目都包含其中。
在切片操作中提供第三个参数,这一参数将被视为切片的步长(Step)
当步长为 2 时,我们得到的是第 0、2、4…… 位项目。当步长为 3 时,我们得到的是第 0、3……位项目。
序列的一大优点在于你可以使用同样的方式访问元组、列表与字符串。

集合

集合(Set)是简单对象的无序集合(Collection)。当集合中的项目存在与否比起次序或其出现次数更加重要时,我们就会使用集合。
通过使用集合,你可以测试某些对象的资格或情况,检查它们是否是其它集合的子集,找到两个集合的交集,等等。

>>> 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'}

引用

当你创建了一个对象并将其分配给某个变量时,变量只会查阅(Refer)某个对象,并且它也不会代表对象本身。也就是说,变量名只是指向你计算机内存中存储了相应对象的那一部分。这叫作将名称绑定(Binding)给那一个对象。
如下实例中,引用即是=。

print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
 # mylist 只是指向同一对象的另一种名称
mylist = shoplist

 # 我购买了第一项项目,所以我将其从列表中删除
del shoplist[0]

print('shoplist is', shoplist)
print('mylist is', mylist)
 # 注意到 shoplist 和 mylist 二者都
 # 打印出了其中都没有 apple 的同样的列表,以此我们确认
 # 它们指向的是同一个对象

print('Copy by making a full slice')
 # 通过生成一份完整的切片制作一份列表的副本
mylist = shoplist[:]
 # 删除第一个项目
del mylist[0]

print('shoplist is', shoplist)
print('mylist is', mylist)
 # 注意到现在两份列表已出现不同

输出:

Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

你要记住如果你希望创建一份诸如序列等复杂对象的副本(而非整数这种简单的对象(Object)),你必须使用切片操作来制作副本。如果你仅仅是将一个变量名赋予给另一个名称,那么它们都将“查阅”同一个对象,如果你对此不够小心,那么它将造成麻烦。

有关字符串的更多内容

字符串也是一种对象,并且它也具有自己的方法,可以做到检查字符串中的一部分或是去掉空格等几乎一切事情!
你在程序中使用的所有字符串都是 str 类下的对象。

# 这是一个字符串对象
name = 'Swaroop'

if name.startswith('Swa'):
    print('Yes, the string starts with "Swa"')

if 'a' in name:
    print('Yes, it contains the string "a"')

if name.find('war') != -1:
    print('Yes, it contains the string "war"')

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))

输出:

Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China

startwith 方法用于查找字符串是否以给定的字符串内容开头。
in 运算符用以检查给定的字符串是否是查询的字符串中的一部分。
find 方法用于定位字符串中给定的子字符串的位置。如果找不到相应的子字符串,find 会返回 -1。
str 类同样还拥有一个简洁的方法用以 联结(Join)序列中的项目,其中字符串将会作为每一项目之间的分隔符,并以此生成并返回一串更大的字符串。

摘自:

https://bop.molun.net/12.data_structures.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值