目录
②与if函数、while函数、input函数、for函数、split函数结合使用
②if函数、while函数、input函数、for函数、split函数结合使用
1.pop方法的用法和实例
(1)语法:list.pop([index])
index:指定删除的列表元素 的位置。可选,默认为删掉最后一个位置(即index=-1)的元素。
注意:索引值不能超出列表范围,列表也不能为空值否则会报错。
(2)用法:删掉列表指定位置的元素,返回值为剔除值。
(3)实例
①简单的用法实例
#实例①
list
list
#输出结果为:= ['j','h']
list.pop()
#返回结果为'h'
#需要查看list值可直接调用list
list
#输出结果为:['j']
#实例②
list = ['key','help','computer','value'] #定义列表list
del_list =list.pop(-2) #剔除掉倒数第二个元素即‘computer’
print('删除的对象为del_list:',del_list)
print('列表list为:',del_list)
#输出结果为:
#删除的对象为del_list: computer
#列表list为: computer
②与if函数、while函数、input函数、for函数、split函数结合使用
while True:
string = input('请输入a值:')
list1 = string.split()
list2 = list1.copy() #复制相同的list1
print('输出列表值list1为:',list1)
for str in list2: #从左向右迭代
if "'" in str : #判断每个迭代的字符是否有单引号‘"'",有则删掉
pop = list1.pop(list1.index(str)) #删掉第一个表示即为删掉对应位置的值
print('剔除的值为',pop)
elif "," in str : #判断每个迭代的字符是否有",",有则删掉
pop = list1.pop(list1.index(str)) #删掉第一个表示即为删掉对应位置的值
print('剔除的值为',pop)
else:
print('%s不需要剔除哦!'%str)
print('list1的值最终为:',list1)
输出结果:
请输入a值:>? 'hello world,welcome to our world ' #第一个输入的字符串
输出列表值list1为: ["'hello", 'world,welcome', 'to', 'our', 'world', "'"]
剔除的值为 'hello
剔除的值为 world,welcome
to不需要剔除哦!
our不需要剔除哦!
world不需要剔除哦!
剔除的值为 '
list1的值最终为: ['to', 'our', 'world']
请输入a值:>? hello world,welcome to our world #第二个输入的字符串
输出列表值list1为: ['hello', 'world,welcome', 'to', 'our', 'world