python中列表可以修改和删除吗,python列表中删除

  python中列表可以修改和删除吗,python列表中删除

  

  列表的查

  a=[klvchen , tom , jack , james , lily , lucy]

  打印(甲[1:4])结果:

  [汤姆,杰克,詹姆斯]注意:

  列表的切片的下标以0 为开始。即:下标0 - klvchen,下标1 -汤姆,下标5 -露西。

  列表的切换顾头不顾尾,例如:a [1:4],则不会取到列表下标为四的元素

  从左到右,取到最后:

  a=[klvchen , tom , jack , james , lily , lucy]

  打印(甲[1:])结果:

  [汤姆,杰克,詹姆斯,莉莉,露西]从左到右,取到倒数第二个值:

  a=[klvchen , tom , jack , james , lily , lucy]

  打印(a[1:-1])结果:

  [汤姆,杰克,詹姆斯,莉莉]从左到右,隔一个去取:

  a=[klvchen , tom , jack , james , lily , lucy]

  打印(a[1:2])结果:

  [汤姆,詹姆斯,露西]从右到左,一个一个去取:

  a=[klvchen , tom , jack , james , lily , lucy]

  打印(a[:-1])结果:

  [詹姆斯,杰克,汤姆,克拉夫兴]从右到左去取

  a=[klvchen , tom , jack , james , lily , lucy]

  打印(a[-2:-4:-1])结果:

  rush:php;toolbar:false">['lily','james']列表的增

  append 方法默认插到最后一个位置

  

a=["klvchen","tom","jack","james","lily","lucy"]

  a.append("mary")

  print(a)

结果:

  

['klvchen','tom','jack','james','lily','lucy','mary']
insert 方法将数据插入到任意一个位置

  

a=["klvchen","tom","jack","james","lily","lucy"]

  a.insert(1,"mary")

  print(a)

结果:

  

['klvchen','mary','tom','jack','james','lily','lucy']
extend 方法可在列表的末尾一次性追加另一个序列中的多个值

  

a=["klvchen","tom","jack"]

  b=["james","lily","lucy"]

  a.extend(b)

  print(a)

结果:

  

['klvchen','tom','jack','james','lily','lucy']
相关推荐:《Python视频教程》

  列表的改

  

a=["klvchen","tom","jack","james","lily","lucy"]

  a[1]="tom2"

  print(a)

结果:

  

['klvchen','tom2','jack','james','lily','lucy']

  a=["klvchen","tom","jack","james","lily","lucy"]

  a[1:3]=["tom2","jack2"]

  print(a)

结果:

  

['klvchen','tom2','jack2','james','lily','lucy']
列表的删

  remove 方法

  

a=["klvchen","tom","jack","james","lily","lucy"]

  a.remove("tom")

  print(a)

结果:

  

['klvchen','jack','james','lily','lucy']
pop 方法

  

a=["klvchen","tom","jack","james","lily","lucy"]

  b=a.pop(1)

  print(a)

  print(b)

结果:

  

['klvchen','jack','james','lily','lucy']

  tom

注意 pop 方法会返回删除的元素

  del 方法

  

a=["klvchen","tom","jack","james","lily","lucy"]

  dela[1]

  print(a)

结果:

  

['klvchen','jack','james','lily','lucy']

  a=["klvchen","tom","jack","james","lily","lucy"]

  dela

  print(a)

结果:

  

NameError:name'a'isnotdefined
注意:del a 把列表a从内存删除了,所以打印 a 列表程序会报错

  列表元素的统计

  

list=['a','a','b','c']

  res=list.count('a')

  print(res)

结果:

  

2
列表的排序

  sort 方法

  

a=["klvchen","tom","jack","james","lily","lucy"]

  print(a)

  a.sort()

  print(a)

结果:

  

['klvchen','tom','jack','james','lily','lucy']

  ['jack','james','klvchen','lily','lucy','tom']

reverse 方法

  

a=["klvchen","tom","jack","james","lily","lucy"]

  print(a)

  a.reverse()

  print(a)

结果:

  

['klvchen','tom','jack','james','lily','lucy']

  ['lucy','lily','james','jack','tom','klvchen']


郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: