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', 'Nginx', 'MySQL', 'PHP', 'Apache']
I will sort my list now
Sorted list is ['Apache', 'Linux', 'MySQL', 'Nginx', 'PHP']
The first item Apache
delete first item
list is now ['Linux', 'MySQL', 'Nginx', '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', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
3. 字典
字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。
# Deleting a key/value pair
del contacts['Support']
print '\nThere are %d contacts in the address-book\n' % 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']
输出