list: Python中内置的有序数据结构,即数组。由于Python是动态语言,因此数组元素的类型没有限定。
- classmates = [“Michael”, “David”,”Bob”,”Tracy”]
- 空列表:empty_list = []
- 使用负数来表示倒叙,即索引-1来表示最后一项:classmates[-1]打印出Tracy,classmates[-4]打印出Michael,注意倒叙不是从0开始,因为-0和0没区别。
- list.insert(index, data) 在指定的位置插入指定内容。
- list.append(new_list) 在list结尾将整个new_list作为一个元素插入。
- list.extend(new_list)在list结尾将new_list的元素逐一插入。
- list.pop()返回并删除list的最后一个元素。
推导公式的多层嵌套:
# 例:打印1~999中个位数和百位数相同的数字,每个for/if语句都是包含的关系。
1 print(x*100 + y*10 + z for x in range(10) for y in range(10) for z in range(10) if x > 0 and x == z)
for语句中获得list下标:enumerate(list)会将list转换成(index,item)的tuple。
1 >>> L=['abc','bcd','cde'] 2 >>> for n in enumerate(L): 3 ... print(n) 4 ... 5 (0, 'abc') 6 (1, 'bcd') 7 (2, 'cde') 8 >>> for index,item in enumerate(L): 9 ... print(index,',',item) 10 ... 11 0 , abc 12 1 , bcd 13 2 , cde