码迷,mamicode.com
首页 > 编程语言 > 详细

python如何操作列表-list

时间:2017-08-23 00:49:47      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:code   移除   class   补充   排列   style   reverse   pre   asc   

一、创建一个列表

用把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:

>>> name_list = ["root", "gm", "hlr"]

 

 

二、访问列表中的值

使用下标索引来访问列表中的值,与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。

>>> name_list
[root, gm, hlr]

 

三、查看列表可进行的操作

>>> help(name_list)
·················
>>> dir(name_list)
[‘append, clear, copy, count, extend, index, insert, pop, remove, reverse, sort]
  append("STRING"):向列表的末尾追加一个新的值

  clear:

  copy:

  count("STRING"):统计某字符串或值在列表中出现的次数

  extend:

  index("STRING"):某值在列表中第一次出现的位置

  insert(N,"STRING"):向列表的位置N处插入一个新值

  pop(obj=list[-1]):删除列表某个位置的值,默认为最后一个值

  remove("STRING"):移除列表中某个值的第一个匹配项
  reverse
():列表元素值反序排列   
  
  sort
():对列表内的所以值按照ASCII码进行排序

 

 

四、append

# 原列表

>>> name_list
[root, gm, hlr]

# 新增一个root值

>>> name_list.append("root")

# 新列表

>>> name_list
[root, gm, hlr, root]

 

 

五、count

# 统计root用户在列表中出现的次数

>>> name_list.count("root")
2
# 额外补充,如何删除列表中的root值(此时列表有2个值为root)

>>> name_list
[root, hlr, gm, root]
>>> for i in range(name_list.count("root")):
... name_list.remove("root")
... 
>>> name_list
[hlr, gm]

 

 

六、index

# 原列表

>>> name_list
[root, gm, hlr, root]

# 查看hlr用户在列表第一次出现的位置

>>> name_list.index("hlr")
2

 

 

七、insert

# 原列表

>>> name_list

[root, gm, hlr, root]

# 在列表的位置2处新增一个test用户

>>> name_list.insert(2, "test")

# 新列表

>>> name_list
[root, gm, test, hlr, root]

 

 

八、pop

# 原列表

>>> name_list
[root, gm, test, hlr, root]

# 删除列表位置为2的值

>>> name_list.pop(2)
test

# 新列表
>>> name_list
[root, gm, hlr, root]

# 删除列表最后一个值

>>> name_list.pop()
root

# 新列表
>>> name_list
[root, gm, hlr]

 

 

九、remove

# 原列表
>>> name_list [root, gm, hlr] # 新增一个gm用户
>>> name_list.append("gm") # 新列表 >>> name_list [root, gm, hlr, gm] # 移除第一个gm用户
>>> name_list.remove("gm") # 新列表 >>> name_list [root, hlr, gm]

 

 

十、reverse

# 原列表
>>> name_list
[root, hlr, gm]

# 反向排列列表中元素

>>> name_list.reverse()

# 新列表

>>> name_list
[gm, hlr, root]

 

 

十一、sort

# 原列表

>>> name_list
[root, hlr, gm]

# 对列表进行排序

>>> name_list.sort()

# 新列表
>>> name_list
[gm, hlr, root]

 

 

python如何操作列表-list

标签:code   移除   class   补充   排列   style   reverse   pre   asc   

原文地址:http://www.cnblogs.com/python-gm/p/7414143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!