列表
列表是处理一组有序项目的数据结构,即可以在列表中存储一个序列的项目, 并且列表是可变类型的数据
格式:
list = [元素1,元素2,....]
列表常用方法
列表有以下常用方法,下面通过实例来一一介绍具体用法
append(object) 在列表末尾添加一个对象object
insert(index,object) 在指定索引index插入一个对象object
remove(vlaue) 删除首次出现的value值
pop([index]) 删除索引index指定的值,如果index不指定,删除列表中的最后一个元素
index(value,[start,[stop]]) 返回value出现在列表中的索引
sort() 列表的排序
reverse() 列表的反转
len() 列表的长度
通过索引取值
实例:
list2 = ['a',1,1,['hello,''friend']]
list2[0]
'a'
list2[1]
1
变更列表值
实例:
list2[0]='b'
>>> list2
['b', 1, 1, ['hello,friend']]
列表相加
实例:
list1=['good','morning']
list1 + list2
['good', 'morning', 'b', 1, 1, ['hello,friend']]
列表移除 remove(),移除第一次出现的值
实例:
list2=['b', 1, 1, ['hello,friend']]
>>> list2.remove(1)
>>> list2
['b', 1, ['hello,friend']]
查找值是否在列表中
实例:
list1=['good', 'morning']
list2=['b', 1, ['hello,friend']]
'b' in list1
False
'b' in list2
True
插入列表 insert()
实例:
list3 = ['a','b','c']
list3.insert(1,list1)
print(list3)
['a', ['good', 'morning'], 'b', 'c']
在末尾插入元素 append()
实例:
list1=['good', 'morning']
>>> list1.append('friend')
>>> print(list1)
['good', 'morning', 'friend']
排序 sort()
实例:
list4 = ['a','d','b']
>>> list4.sort()
>>> print(list4)
['a', 'b', 'd']
反转 reverse()
list4 = ['a','d','b']
>>> list4.reverse()
>>> print(list4)
['b', 'd', 'a']
删除元素 pop()
list4=['b', 'd', 'a']
list4.pop()
print(list4)
['b', 'd']
指定具体index
list4 = [4,'python','hello']
list4.pop(1) ##删除索引值为1的元素
print(list4)
[4, 'hello']
统计列表长度 len()
list1 = ['good','moring','friend']
len(list1)
3
列表常用操作
1. 遍历列表
遍历列表中的所有元素,可以通过for循环进行遍历
实例:
names = ['mike','steven','marcus']
for name in names:
print(name)
执行后可以将列表中每个元素打印出来
mike
steven
marcus
实例2:
for name in names:
print("Good morning " + name.title())
Good morning Mike
Good morning Steven
Good morning Marcus
2. 列表切片
实例1:
>>> name = ['mike','jack','tony','steven']
>>> print(name[0:2])
['mike', 'jack']
>>> print(name[::])
['mike', 'jack', 'tony', 'steven']
>>> print(name[-1])
steven
>>> print(name[:-1])
['mike', 'jack', 'tony']
>>> print(name[2:])
['tony', 'steven']
实例2:
对列表前三个元素进行切片
name = ['mike','jack','tony','steven']
for people in name[:3]:
print(people.title())
Mike
Jack
Tony
3.. 列表生成式
通过列表生成式for循环和创建新元素将三四行代码编写成一行
number = [value**2 for value in range(1,11)]
>>> print(number)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]