1、创建列表
*创建普通列表
>>> member = ['尘封','破冰','python']
>>> member
['尘封', '破冰', 'python']
*创建一个混合列表
>>> mix = [1,'尘封',3.14,[1,2,3]]
>>> mix
[1, '尘封', 3.14, [1, 2, 3]]
*创建一个空列表
>>> empty = []
>>> empty
[]
2、向列表添加元素
append()函数:只能添加一个元素
>>> member.append('一直播')
>>> member
['尘封', '破冰', 'python', '一直播']
extend()函数:可以添加多个元素,需要注意的是添加的时候只能是个列表[]
>>> member.extend(['战鲨','小咖秀'])
>>>
>>> member
['尘封', '破冰', 'python', '一直播', '战鲨', '小咖秀']
insert()函数:列表里面固定插入第几个元素
>>> member.insert(0,'玉婷') 玉婷插入列表内的第一位
>>> member
['玉婷', '尘封', '破冰', 'python', '一直播', '战鲨', '小咖秀']
3、有列表name = ['f','i','h','c'],如果在‘i’和‘h’之间插入元素‘s’:
>>> name = ['f','i','h','c']
>>> name.insert(2,'s')
>>> name
['f', 'i', 's', 'h', 'c']
二、练习题
1、假设给定以下列表:
member = [‘尘封’,'破冰','泪无痕']
要求将列表修改为:
member = ['尘封','88','破冰','90','泪无痕','95']
方法一:使用insert()和append()方法修改列表
方法二:重新创建一个同名字的列表覆盖
方法一:
>>> member = ['尘封','破冰','泪无痕']
>>> member.insert(1,'88')
>>> member.insert(3,'90')
>>> member.append('95')
>>> member
['尘封', '88', '破冰', '90', '泪无痕', '95']
方法二:
>>> member = ['尘封','破冰','泪无痕']
>>> member = ['尘封', '88', '破冰', '90', '泪无痕', '95']
>>> member
['尘封', '88', '破冰', '90', '泪无痕', '95']
2、利用for循环打印member列表中的每个内容:
member =['尘封', '88', '破冰', '90', '泪无痕', '95']
for each in member:
print(each)
================= RESTART: /Users/wufq/Desktop/member_for.py =================
尘封
88
破冰
90
泪无痕
95
3、上一题打印的样式不好看,修改为以下样式【至少使用两种方式】
第一种:
member =['尘封', '88', '破冰', '90', '泪无痕', '95']
count =0
length = len(member)
while count < length:
print(member[count],member[count+1])
count +=2
================== RESTART: /Users/wufq/Desktop/优化member.py ==================
尘封 88
破冰 90
泪无痕 95
----代码解析:length = len(member) 把数组转换成长度,while count < length: 在固有长度循环输出,并且每次打印两个数字,关键:count +=2(count数每次加2,输出)
第二种:
member =['尘封', '88', '破冰', '90', '泪无痕', '95']
#rang(len(member)):代表len(member)的数字序列:0,1,2,3,4,5
for each in range(len(member)):
if each%2 == 0:
print(member[each],member[each+1])
================= RESTART: /Users/wufq/Desktop/优化member1.py =================
尘封 88
破冰 90
泪无痕 95
>>>