python - 列表、元组、字典、序列、集合

一、列表

 list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目。假想你有一个购物列表,上面记载着你要买的东西,你就容易理解列表了。只不过在你的购物表上,可能每样东西都独自占有一行,而在Python中,你在每个项目之间用逗号分割。

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

#!/usr/bin/python
shoplist=['apple','mango','carrot','banana']
print('I have',len(shoplist),'items to purchase')
print('These items are: ',end=' ')
for items in shoplist:
    print(items,end=' ')
print('\n I also have to by rice.')
shoplist.append('rice')
print('My shoppinglist is now', shoplist)
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)
olditem=shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)

结果:
I have 4 items to purchase
These items are:  apple mango carrot banana 
 I also have to by rice.
My shoppinglist is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
  

如何工作:

变量 shoplist 是将要去市场的人的一个购物单。在 shoplist 中,进存储了各项要 买的东西的名字,但你也可以增加任意类型对象,包括数字甚至列表。

使用了 for...in 循环通过列表中的各项来进行重复。到现在,你一定明白了列表也是一个序列。序列的特殊性会在后一节讨论。

注意 print 函数的 end 关键参数来表示以空格结束输出,而不是通常的换行。

接下来,用 append 方法来给列表对象增加一项,像前面讨论的那样。然后,通过简单地将列表传送给 print 语句漂亮地将列表的内容输出,来检查的确给类表增加了那一项。

然后,用 sort 方法将列表进行排序。理解这一方法影响了列表本身,没有返回修改后的列表是重要的 —— 这与字符串起作用的方式不同。这就是我们所说的列表是易变的,字符串是不可变的。

接下来,当我们在市场买完了一项时,我们想将其从列表中移去。用 del 语句来实现。这儿,我们提到了想要从列表中移去那一项,用 del 语句将其移除。指定想要移除列表中的第一项因此用 del shoplist[0](记住,Python 中从 0 开始计算)。

如果想知道通过列表对象定义的所有方法,用 help(list) 获取更多细节。

二、元组

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

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

#!/usr/bin/python
zoo = ('python','elephant','penguin')
print('Number of animals in the zoo is', len(zoo))
new_zoo = ('monkey','camel',zoo)
print('Number of animals 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 animals brought from old zoo is',new_zoo[2][2])
print('Number of animals in the zoo is',len(new_zoo)-1+len(new_zoo[2]))

结果:
Number of animals in the zoo is 3
Number of animals 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 animals brought from old zoo is penguin
Number of animals in the zoo is 5

它如何工作:

变量 zoo 是一个元组,我们看到 len 函数可以用来获取元组的长度。这也表明元组也是一个序列。

由于老动物园关闭了,我们把动物转移到新动物园。因此,new_zoo 元组包含了一些已经在那里的动物和从老动物园带过来的动物。回到话题,注意元组之内的元组不会失去它的特性。

我们可以通过一对方括号来指明某个项目的位置从而来访问元组中的项目,就像我们对列表的用法一样。这被称作索引运算符。我们使用 new_zoo[2] 来访问 new_zoo中的第三个项目。我们使用 new_zoo[2][2] 来访问 new_zoo 元组的第三个项目的第三个项目。如果理解习惯的这相当简单。

三、字典

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

注意,你只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以把不可变或可变的对象作为字典的值。基本说来就是,你应该只使用简单的对象作为键。

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

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

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

#!/usr/bin/python
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 {0} contacts in the address-book\n'.format(len(ab)))
for name,address in ab.items():
    print('Conact {0} at {1}'.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
Conact Swaroop at swaroop@swaroopch.com
Conact Larry at larry@wall.org
Conact Matsumoto at matz@ruby-lang.org
Guido's address is guido@python.org

如何工作:

我们使用已经介绍过的标记创建了字典 ab。然后我们使用在列表和元组章节中已经讨论过的索引操作符来指定键,从而使用键/值对。我们可以看到字典的语法同样十分简单。

我们可以使用索引操作符来寻址一个键并为它赋值,这样就增加了一个新的键/值对,就像在上面的例子中我们对 Guido 所做的一样。

我们可以使用我们的老朋友 |——del 语句来删除键/值对。我们只需要指明字典和用索引操作符指明要删除的键,然后把它们传递给 del 语句就可以了。执行这个操作的时候,我们无需知道那个键所对应的值。

接下来,我们使用字典的 items 方法,来使用字典中的每个键/值对。这会返回一个元组的列表,其中每个元组都包含一对项目 —— 键与对应的值。我们抓取这个对,然后分别赋给 for..in 循环中的变量 name address 然后在 for -块中打印这些值。

我们可以使用 in 操作符来检验一个键/值对是否存在,或者使用 dict 类的 has_key方法。你可以使用 help(dict) 来查看 dict 类的完整方法列表。

四、序列

列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?

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

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

#!/usr/bin/python
shoplist = ['apple','mango','carrot','banana']
name = 'swaroop'
#indexing or  'Subscription' operation
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('Character 1 to 3 is', name[1:3])
print('Character 2 to end is', name[2:])
print('Character 1 to -1 is', name[1:-1])
print('Character 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']
Character 1 to 3 is wa
Character 2 to end is aroop
Character 1 to -1 is waroo
Character start to end is swaroop

如何工作:

首先,我们来学习如何使用索引来取得序列中的单个项目。这也被称作是下标操作。每当你用方括号中的一个数来指定一个序列的时候,Python 会为你抓取序列中对应位置的项目。记住,Python 0 开始计数。因此,shoplist[0] 抓取第一个项目,shoplist[3] 抓取 shoplist 序列中的第四个元素。

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

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

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

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

你可以用负数做切片。负数用在从序列尾开始计算的位置。例如,shoplist[:-1] 会返回除了最后一个项目外包含所有项目的序列切片。你也可以给切片规定第三个参数,就是切片的步长(默认步长是 1)。

#!/usr/bin/python
shoplist = ['apple','mango','carrot','banana']
print (shoplist[::1])
print (shoplist[::2])
print (shoplist[::3])
print (shoplist[::-1])

结果:
['apple', 'mango', 'carrot', 'banana']
['apple', 'carrot']
['apple', 'banana']
['banana', 'carrot', 'mango', 'apple']

注意当步长是 2 时,我们得到在位置 0,2,... 的项,当步长是 3 时,得到位置 0,3, 等等的项。

使用 Python 解释器交互地尝试不同切片指定组合,即在提示符下你能够马上看到结果。序列的神奇之处在于你可以用相同的方法访问元组、列表和字符串!

五、集合

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

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

#!/usr/bin/python
bri = set(['brazil','russia','india'])
print('india' in bri)
print('usa' in bri)
bric = bri.copy()
bric.add('china')
print(bric.issuperset(bri))
bri.remove('russia')
print(bri&bric)

结果:
True
False
True
{'brazil', 'india'}


 

 

 

 


 

 

 


 

 


 

 

 

 


 

 

 


 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 


 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农村詹姆斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值