a = [1, 2, 3, 4, 5, 6, 7]
print 'a is', a
print 'element in position 2 is', a[2]
print 'the position of 3 is', a.index(3)
print 'element in position 1~3 are', a[1:4] # half open range
print 'element from position 2 are', a[2:]
print 'element to last but one are', a[:-1]
print 'elements in even position', a[::2]
print 'elements in event position within a range', a[1:-1:2]
a[0] = 0
print 'after change element in position 0:', a
a.append(2)
print 'after append:', a
a.extend([4, 'five'])
print 'after extent:', a
a.remove(2)
print 'after remove element 2:', a
a.pop()
print 'after pop:', a
print 'is 2 in a:', 2 in a
del a[2]
print 'after delete element in position 2:', a
print 'is 2 in a:', 2 in a
a is [1, 2, 3, 4, 5, 6, 7] element in position 2 is 3 the position of 3 is 2 element in position 1~3 are [2, 3, 4] element from position 2 are [3, 4, 5, 6, 7] element to last but one are [1, 2, 3, 4, 5, 6] elements in even position [1, 3, 5, 7] elements in event position within a range [2, 4, 6] after change element in position 0: [0, 2, 3, 4, 5, 6, 7] after append: [0, 2, 3, 4, 5, 6, 7, 2] after extent: [0, 2, 3, 4, 5, 6, 7, 2, 4, 'five'] after remove element 2: [0, 3, 4, 5, 6, 7, 2, 4, 'five'] after pop: [0, 3, 4, 5, 6, 7, 2, 4] is 2 in a: True after delete element in position 2: [0, 3, 5, 6, 7, 2, 4] is 2 in a: True
元组与列表类似, 可以:
a[2]
)index
)in
)a[2:-1]
)但是元组是不可修改的, 不可以:
a[2] = 3
)append
extent
remove
pop
del
元组可以保存不变的数据, 比列表效率更高.
a = (1, 2, 3, 4, 5, 6, 7)
print 'a is', a
print 'is 2 in a:', 2 in a
print 'the position of 7 is:', a.index(7)
a is (1, 2, 3, 4, 5, 6, 7) is 2 in a: True the position of 7 is: 6
字典提供了一种"键(key)"和"值(value)"之间的多对一映射.
from IPython.display import Image, display
d = {
'neta': '捏他',
42: 'the answer to life the universe and everything'
}
print '%d is %s' % (42, d[42])
print 'neta means %s' % d['neta'], 'not 捏她'
display(Image(url='http://goo.gl/tVTG5'))
42 is the answer to life the universe and everything neta means 捏他 not 捏她
字典提供与列表类似的del
和in
操作:
d = {'foo': 'bar', 1: -1, 'bar': 'foo'}
print d
del d['foo']
print d
print 1 in d
{1: -1, 'foo': 'bar', 'bar': 'foo'} {1: -1, 'bar': 'foo'} True