首页 > 其他分享 >1.6 数据结构_列表 lst[index],lst.append(obj),lst[index]=obj,lst.remove(obj),for...in..,切片

1.6 数据结构_列表 lst[index],lst.append(obj),lst[index]=obj,lst.remove(obj),for...in..,切片

时间:2022-10-06 13:25:04浏览次数:57  
标签:index obj 44 42 43 40 lst

#列表的数据处理

   #1.获取元素:lst[index]

   #2.新增元素:lst.append(obj)

  #3.修改元素:lst[index]=obj

  #4.删除元素:lst.remove(obj)

  #5.列表元素很多批量处理  for...in..

  #6.列表数据获取中的切片

————————————————————————————————————————————

##1.获取元素:lst[index]

lst=[40,41,42,43,44]
print(lst[1])             #索引获取列表中元素
#运行输出
41

 ##2.新增元素:lst.append(obj)

lst=[40,41,42,43,44]
lst.append(100)             #列表后增加元素
#运行输出
[40, 41, 42, 43, 44, 100]

#3.修改元素:lst[index]=obj

 

lst=[40,41,42,43,44,100]
lst[1]=410                  #通过索引修改列表元素
print(lst)
#运行输出
[40, 410, 42, 43, 44, 100]

 

#4.删除元素:lst.remove(obj)

 

lst=[40, 410, 42, 43, 44, 100]
lst.remove(42)                          #删除列表中的元素
print(lst)
#运行输出
[40, 410, 43, 44, 100]

 

# #5.列表元素很多批量处理  for...in..

lst=[40, 410, 43, 44, 100]
for i in range(0,len(lst)):          #长度方式遍历
    print(lst[i])

for item in lst:                     #直接列表方式遍历
    print(item)

#6.列表数据获取中的切片

 

'''列表有双向索引,从左到右为正数,0,1,2,3,..
  从右到左,  -1,-2,-3,,,'''
lst=[40,41,42,43,44]
lst1=lst[1:]                     #从标号(索引)的位置开始,一直切到最后一个元素
print('第1个',lst1) 
lst2=lst[1:3]                   #左闭右开 ,包含索引为1的元素,但是不包含索引为3的元素
print('第2个',lst2)
lst3=lst[:]                      #重头到尾复制一遍
print('第3个',lst3)
print('第4个',lst[-4:])            #负数索引。从右到左第一个索引为-1
#运行输出
第1个 [41, 42, 43, 44]
第2个 [41, 42]
第3个 [40, 41, 42, 43, 44]
第4个 [41, 42, 43, 44]

 

标签:index,obj,44,42,43,40,lst
From: https://www.cnblogs.com/988MQ/p/16757438.html

相关文章