python 删除list中的第一个元素

目录

1.python 删除list中元素三种方式(一般)

1. pop()

2.del

3.remove

2.嵌套数组删除存在的问题


1.python 删除list中元素三种方式(一般)

1. pop()

1.默认删除最后一个元素.pop()中也可以传入参数,为list的索引
2.pop() 接收的是索引,无参的情况下删除的是最后一个元素(典型的栈的特性)
3.pop() 存在返回值,返回的是删除的元素值

list=[11,12,13,14,15]
list=[11,12,13,14,15]
list.pop()
print(list.pop())
print(list)

#output
14
[11, 12, 13]

2.del

list=[11,12,13,14,15]
del(list[1])
print(list)

#output
[11, 13, 14, 15]

3.remove

remove() 的参数是具体的元素值,而不是索引,

list=[11,12,13,14,15]
list.remove(11)
print(list)

#output
[12, 13, 14, 15]

2.嵌套数组删除存在的问题

存在于嵌套list中, 如果list1中的一个元素发生改变,list0也会变化.
目的:list0生成后不随list1的改变而改变

if(len(first_images)==12): #获取到了1分钟内的12个图像

         grey_images.append(to_grey(first_images))                  
         first_images.clear()

         if(len(grey_images)==5): #获得了5分钟的图片
            images.append(grey_images)
			print("image1前的shape:")
			arr1 = np.array(images)
			print(arr1.shape)

            del(grey_images[0])

			print("image1之后的shape:")
			arr1 = np.array(images)
			print(arr1.shape)
			                        

结果:image1前的shape和image1之后的shape并不一样.删除元素后比之前的少了一个元素.因为list存放的是索引,并不是实际的值

Solution:

思路:将索引改为实际的值,然后再删除
具体步骤:
1.创建一个新的数组
2.对原数组的元素依次放入新数组中.
3.对原数组进行元素删除.
这样新数组的值并不会发生改变.因为新数组的元素不再是引用,而是实际的值

if(len(first_images)==12): #获取到了1分钟内的12个图像

	grey_images.append(to_grey(first_images))
	first_images.clear()
	
	if(len(grey_images)==5): #获得了5分钟的图片
		    grey_images_val=[]
		    for t in range(5):
		        grey_images_val.append(grey_images[i])
		 
		    images.append(grey_images_val)
		    print("grey的length:")
		    print(len(grey_images))
		
		    print("image1前的shape:")
		    arr1 = np.array(images)
		    print(arr1.shape)
		
		    grey_images.pop()
		    print("image1之后的shape:")
		    arr1 = np.array(images)
		    print(arr1.shape)

结果:image1前的shape和image1之后的shape此时相同

 

 

  • 6
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值