Lists: a container of things that are organized in order from first to last.
e.g.
hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]
2-dimensional (2D) list(二维列表):
That's a list in a list like this: [[1,2,3],[4,5,6]]
列表可以在以后再添加元素,使用append:
elements = []
for i in range(0, 6):
print "Adding %d to the list." % i
elements.append(i)
for i in elements:
print "Element was: %d" % i
读取元素 Accessing Elements of Lists
animals = ['bear', 'tiger', 'penguin', 'zebra']
bear = animals[0]
注意是从0开始的,这类的数字被称为“基数(cardinal number)”,相对的是“序数(ordinal number)”
同时可以是负数,顺序倒过来,比如 zebra = animals[-1] 会读取最后一个
相关函数:
1. stuff.split(' ') 按照' '(空格)分割stuff(stuff为字符串)为list,若为't',则结果为['All good ', 'hing come ', 'o ', 'hose who wai', '.'](其中stuff = "All good things come to those who wait.")
2. sorted(words) 对list进行排序
3. words.pop(0) 找出第一个(并移出列表)
words.pop(-1) 找出最后一个(并移出列表)
words.pop() 找出最后一个(并移出列表)
4. len(stuff) 返回stuff的元素个数
5. ' '.join(stuff) 将stuff中元素连接起来变成字符串,中间加' '
'#'.join(stuff[3:5]) 将第3 < i <= 5个元素(即4,5两个)连接起来变成字符串,中间加'#'
没有评论:
发表评论