列表
在Python中,用方括号([])来表示列表,并用逗号来分隔其中的元素。下面是一个简单的 列表示例
invite_list=['fc','xy','dl','wsh','lxr','zdt'] #创建一个列表
invite_list.append('zr') # list.append()往列表末添加
print(invite_list)
invite_list.insert(0,'weg') # list.insert(索引,'要添加的')
print(invite_list)
poped_invite_list=invite_list.pop() # list.pop()可以将列表末顶出,也可指定:.pop()
print("poped_invite is :",poped_invite_list)# list.reverse可以永久该改变列表顺序,输出直接print
pop = invite_list.pop(0) # .pop()方法将列表最后元素顶出,将值赋给pop这个变量
print("pop is:",pop)
print("now invite_list is :",invite_list) # invite_list.sort() #sort方法,重新排列列表
del invite_list[0] #del删除列表某一项,索引从0开始以此类推,-1是最后一个往前推是-2
print('临时顺序',invite_list)
#遍历整个列表
for i in invite_list:
print ('i invite ',i,'come here')
invite_list.sort() #也可以用.sort(reverse=True),或者sorted()
print("正式顺序:",sorted(invite_list))
for i in invite_list:
print('I invite ',i,' come here ')
运行结果:
[‘fc’, ‘xy’, ‘dl’, ‘wsh’, ‘lxr’, ‘zdt’, ‘zr’]
[‘weg’, ‘fc’, ‘xy’, ‘dl’, ‘wsh’, ‘lxr’, ‘zdt’, ‘zr’]
poped_invite is : zr
pop is: weg
now invite_list is : [‘fc’, ‘xy’, ‘dl’, ‘wsh’, ‘lxr’, ‘zdt’]
临时顺序 [‘xy’, ‘dl’, ‘wsh’, ‘lxr’, ‘zdt’]
i invite xy come here
i invite dl come here
i invite wsh come here
i invite lxr come here
i invite zdt come here
正式顺序: [‘dl’, ‘lxr’, ‘wsh’, ‘xy’, ‘zdt’]
I invite dl come here
I invite lxr come here
I invite wsh come here
I invite xy come here
I invite zdt come here