Python数据基础类型-列表

1,列表的创建

list1 = ['hello', 'world', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = list() #创建空列表
list5 = [] #创建空列表

2,访问列表的值

  列表的数据访问需要使用索引序号。 list1 = ['hello', 'world', 19, 20]

list2 = [1, 2, 3, 4, 5 ]
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
输出结果:
list1[0]: hello
list2[1:5]: [2, 3, 4, 5]

3,数值更新

  列表内容的更新可以直接使用索引序号,进行内容的更新,也可以使用append方法。insert( )在列表的任何位置添加新元素。

list1 = ['hello', 'world', 19, 20]
print list1
list1[0] = "HELLO"
print list1
list1.append(first)
print list1
list1.insert(0,'111111')
运行结果:
['hello', 'world', 19, 20]
['HELLO', 'world', 19, 20]
['HELLO', 'world', 19, 20, 'first']
['111111', 'HELLO', 'world', 19, 20, 'first']

4,列表元素删除

  列表元素的删除使用del语句,也可以使用remove方法,也可使用pop()方法。

猜你喜欢

转载自www.cnblogs.com/felix2008/p/11326406.html