首页 > 代码库 > 1.2数据类型(list)

1.2数据类型(list)

列表创建

创建一个列表,只要用逗号分隔不同的数据项使用方括号括起来即可,例如:

first_list = ["hello","python",1900,1970]

列表访问

使用下标索引访问列表中的值,也可通过方括号进行截取。例如:

>>> first_list = ["hello","python",1900,1970]
>>> first_list[0]
‘hello‘
>>> first_list[1:3]
[‘python‘, 1900]

列表更新

可以索引对列表的数据项进行修改或更新,也可用append方法来增加列表项,例如

>>> first_list = ["hello","python",1900,1970]
>>> first_list[1] = "yangyang"
>>> first_list
[‘hello‘, ‘yangyang‘, 1900, 1970]

append例子,例如:
>>> first_list = ["hello","python",1900,1970]

>>> first_list.append(2017)

>>> first_list
[‘hello‘, ‘yangyang‘, 1900, 1970, 2017]

列表元素删除

使用del删除列表中的元素,例如:

>>> first_list = ["hello","python",1900,1970]
>>> del first_list[3]
>>> first_list
[‘hello‘, ‘python‘, 1900]

列表截取

>>> first_list = ["hello","python",1900,1970]
>>> first_list[1]
‘python‘
>>> first_list[-2]
1900
>>> first_list[1:3]
[‘python‘, 1900]
>>> first_list[1:]
[‘python‘, 1900, 1970]
>>> first_list[-1:-3:-1]
[1970, 1900]

列表操作符:+、*、[]、[:]、in、not in、for i in list

 a = ["hello","python"],b = ["hello","yangyang"]

操作符 描述  实例 
 +  组合  

>>> a = ["hello","python"]
>>> b = ["hello","yangyang"]
>>> a + b
[‘hello‘, ‘python‘, ‘hello‘, ‘yangyang‘]

 重复  

>>> a * 4
[‘hello‘, ‘python‘, ‘hello‘, ‘python‘, ‘hello‘, ‘python‘, ‘hello‘, ‘python‘]

[] 索引

>>> a[0]
‘hello‘

[:] 截取

>>> a[0:2]
[‘hello‘, ‘python‘]

 in  成员运算符,元素在列表中返回True  

>>> "hello" in a
True

 not in  成员运算符,元素不在列表中返回True  

>>> "world" not in a
True

 for i in list  迭代  

>>> for i in a:
print i

hello
python

 

 

1.2数据类型(list)