可以使用len获取列表的长度,使用[]访问列表中的元素;列表的索引从0开始
colors = [\'red\', \'blue\', \'green\']
print colors[0] ## red
print colors[2] ## green
print len(colors) ## 3
当把列表赋值给变量时,并不是生成一个列表的拷贝,而只是使被赋值变量指向了该列表。
b = colors ###Does not copy the list
For var in List 是访问数组元素最简单的方式(其他集合一样适用)。[在循环的过程中,不要增加或者删除列表中的元素]
squares = [1, 4, 9, 16]
sum = 0
for num in squares:
sum += num
print sum ## 30
\”IN\”语句可以轻松的测试某元素是否存在于列表中。
根据测试结果,返回True/False
list = [\'larry\', \'curly\', \'moe\']
if \'curly\' in list:
print \'yay\'
range(n)函数可以返回从0开始到n-1的数字。
## print the numbers from 0 through 99
for i in range(100):
print i
常用的List方法
list.append(elem) — 在列表末尾增加一个元素
list.insert(index,elem) — 在给定的索引位置新增一个元素
list.extend(list2) — 将list2中的元素,新增到list列表末尾
list.index(elem) — 查找元素elem,并返回该元素的索引
list.remove(elem) — 查找元素elem,并删除
list.sort() — 对list列表排序(改变列表list),且没有返回值
list.reverse() — 对list列表转置(改变列表list),且没有返回值
list.pop(index) — 根据index索引,移除,并且返回对应的元素
list = [\'larry\', \'curly\', \'moe\']
list.append(\'shemp\') ## append elem at end
list.insert(0, \'xxx\') ## insert elem at index 0
list.extend([\'yyy\', \'zzz\']) ## add list of elems at end
print list ## [\'xxx\', \'larry\', \'curly\', \'moe\', \'shemp\', \'yyy\', \'zzz\']
print list.index(\'curly\') ## 2
list.remove(\'curly\') ## search and remove that element
list.pop(1) ## removes and returns \'larry\'
print list ## [\'xxx\', \'moe\', \'shemp\', \'yyy\', \'zzz\']
切片([] 和 [:])
aString = \'abcd\'
final_index = len(aString) - 1
本例中的最后一个索引是final_index.我们可以使用[:]访问任意的子串。
对任何范围内的[start:end],都不包括end.假设索引值是X,那么start <=x < end
正向索引
正向索引时,索引值开始于0,结束于总长度减1
>>> aString[0]
\'a\'
>>> aString[1:3]
\'bc\'
>>> aString[2:4]
\'cd\'
>>> aString[4]
Traceback (innermost
IndexError: string index out of range
反向索引
在进行反向索引操作时,是从-1开始,向字符串的开始方向计数,到字符串长度的负数为索引的结束
final_index = -len(aString)
= -4
>>> aString[-1]
\'d\'
>>> aString[-3:-1]
\'bc\'
>>> aString[-4]
\'a\'
默认索引
如果开始索引或者结束索引未指定,则分别以字符串的第一个和最后一个索引值为索引
>>> aString[2:]
\'cd\'
>>> aString[1:]
\'bcd\'
>>> aString[:-1]
\'abc\'
>>> aString[:]
\'abcd\'