Python中3种内建数据结构:列表、元组和字典
|
Python中有3种内建的数据结构:列表、元组和字典。参考简明Python教程
列表中的项目应该包括在方括号中,这样Python就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。由于你可以增加或删除项目,我们说列表是 可变的 数据类型,即这种类型是可以被改变的。
#!/usr/bin/env python
#coding:utf8
list = ['Linux','Nginx','MySQL','PHP']
print 'These items are:',for item in list:
print item,print 'nadd Apache.'
list.append('Apache')
print 'list is now',list
print 'nI will sort my list now'
list.sort()
print 'Sorted list is %s' % list
print 'nThe first item ',list[0]
item0 = list[0]
print 'delete first item'
del list[0]
print 'list is now',list
输出 $python using_list.py These items are: Linux Nginx MySQL PHP add Apache. list is now ['Linux','PHP','Apache'] I will sort my list now Sorted list is ['Apache','Linux','PHP'] The first item Apache delete first item list is now ['Linux','PHP'] 2. 元组
#!/usr/bin/env python
#coding:utf8
zoo = ('wolf','elephant','penguin')
print 'Number of animals in the zoo is',len(zoo)
new_zoo = ('monkey','dolphin',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 animal brought from old zoo is',new_zoo[2][2]
输出
$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey',('wolf','penguin'))
Animals brought from old zoo are ('wolf','penguin')
Last animal brought from old zoo is penguin
3. 字典 注意,你只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以不可变或可变的对象作为字典的值。基本说来就是,你应该只使用简单的对象作为键。 键值对在字典中以这样的方式标记:d = {key1 : value1,key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。 记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。 字典是dict类的实例/对象。
#!/usr/bin/env python
#coding:utf8
contacts = { 'Admin' : 'admin@jb51.net','Linuxeye' : 'linuxeye@jb51.net','Support' : 'support@jb51.net'
}
print "Linuxeye's address is %s" % contacts['Linuxeye']
# Adding a key/value pair
contacts['test'] = 'test@jb51.net'
# Deleting a key/value pair
del contacts['Support']
print 'nThere are %d contacts in the address-bookn' % len(contacts)
for name,address in contacts.items():
print 'Contact %s at %s' % (name,address)
if contacts.has_key('test'):
print "ntest's address is %s" % contacts['test']
输出 $ python using_dict.py Linuxeye's address is linuxeye@jb51.net There are 3 contacts in the address-book Contact Admin at admin@jb51.net Contact test at test@jb51.net Contact Linuxeye at linuxeye@jb51.net test's address is test@jb51.net (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- python-2.7 – 如何在python中使用webdriver选择下拉列表值
- Python操作Execl 实现自动化填表
- python – Cherrypy返回NotFound:(404,“未找到路径’/’.
- python – 添加数字,然后将元组列为元组列表,但它会丢弃外部
- 如何计算galois字段上的numpy数组?
- Python中optparser库用法实例详解
- Python for Informatics 第11章 正则表达式(一)
- python3使用PyMysql连接mysql数据库实例
- python – Numpy蒙面数组 – 表示缺少值
- 在Python中用split()方法分割字符串的使用介绍
