stay hungry stay foolish

python(数组)

list:

Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。

>>> a=[1,2,3]
>>> a
[1, 2, 3]

insert()

>>> a.insert(1,4)
>>> a
[1, 4, 2, 3]

pop()

>>> a.pop()
3
>>> a
[1, 4, 2]
>>> a.pop(1)
4
>>> a
[1, 2]

倒数

[1, 2]
>>> a[-1]
2

tuple

另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改

>>> b=(1,2,3)
>>> b
(1, 2, 3)
>>> b[1]=2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment

对于只有一个元素的tuple,为了避免与表达式()冲突,后面需要加一个‘,’:

>>> b=(1,)
>>> b
(1,)
>>> b[0]
1
>>> b[1]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: tuple index out of range

list,tuple可以随意组合

>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t
('a', 'b', ['X', 'B'])