首页 > 技术文章 > Python基础:1.数据类型(列表)

imeng 2015-12-15 14:45 原文

提示:python版本为2.7,windows系统

1.列表(List)

  List,是一个有序的集合,可以添加、删除其中的元素。

1 >>> colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']
2 >>> colors
3 ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']

  colors就被成为List,而 【'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple'】则被称为元素。

1 >>> type(colors)
2 <type 'list'>

  用len()方法可以获取到colors的长度

1 >>> len(colors)
2 7

  获取元素,则用索引0,1,2,3,4....不能超过colors的长度。从0开始,最后则是len(colors) - 1。

1 >>> colors[0]
2 'red'
3 >>> colors[1]
4 'orange'
5 >>> colors[5]
6 'indigo'
7 >>> colors[6]
8 'purple'

  超出长度则会报错。

1 >>> colors[7]
2 
3 Traceback (most recent call last):
4   File "<pyshell#10>", line 1, in <module>
5     colors[7]
6 IndexError: list index out of range

 当索引为负数时,则从后往前取,-1开始到-len(colors)

1 >>> colors[-1]
2 'purple'
3 >>> colors[-7]
4 'red'
1 >>> colors[-8]
2 
3 Traceback (most recent call last):
4   File "<pyshell#13>", line 1, in <module>
5     colors[-8]
6 IndexError: list index out of range

 取索引为2与-2开始的所有

1 >>> colors[2:]
2 ['yellow', 'green', 'blue', 'indigo', 'purple']
3 >>> colors[-2:]
4 ['indigo', 'purple']

 取从索引为3的数据到第5个,第一个索引为0开始,第二个索引为1开始的。

1 >>> colors[3:5]
2 ['green', 'blue']

 添加元素,在末尾

1 >>> colors.append('pink')
2 >>> colors
3 ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'pink']

 指定位置添加元素

1 >>> colors.insert(1, 'white')
2 >>> colors
3 ['red', 'white', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'pink']

 删除元素,在末尾

1 >>> colors.pop()
2 'pink'
3 >>> colors
4 ['red', 'white', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']

 删除指定元素,则为pop(索引)

1 >>> colors.pop(1)
2 'white'
3 >>> colors
4 ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']

 修改元素,直接赋值修改

1 >>> colors[0] = 'white'
2 >>> colors
3 ['white', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']

 一个List中的类型不一定都是相同的,也可以有数字,列表等在里面

1 >>> colors.append(['red', 'black'])
2 >>> colors
3 ['white', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black']]
4 >>> type(colors[7])
5 <type 'list'>
6 >>> colors[7][0]
7 'red'
8 >>> colors[7][1]
9 'black'

 pop是删除元素并返回这个元素,如果不需要返回还可以用del

1 >>> del colors[0]
2 >>> colors
3 ['orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black']]

 List的操作符

1 >>> # 加号
2 >>> colors + ['white']
3 ['orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black'], 'white']
1 >>> # *号
2 >>> colors * 2
3 ['orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black'], 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black']]
1 >>> # in
2 >>> 'orange' in colors
3 True
4 >>> 'red' in colors
5 False

提示:中文输出的是unicode,元素则是中文

1 >>> money = ['人民币', '美元']
2 >>> money
3 ['\xc8\xcb\xc3\xf1\xb1\xd2', '\xc3\xc0\xd4\xaa']
1 >>> print money[0]
2 人民币
3 >>> print money[1]
4 美元

 

推荐阅读