美文网首页
2018-10-10列表

2018-10-10列表

作者: 未来_9070 | 来源:发表于2018-10-19 22:35 被阅读0次
  • 序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
  • Python有6个序列的内置类型,但最常见的是列表和元组。
  • Python已经内置确定序列的长度以及确定最大和最小的元素的方法。

列表的创建及要求

  • 列表是最常用的Python数据类型,创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可
  • 列表的数据项不需要具有相同的类型
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

  • 在列表末尾添加新的对象
list1 = ["张渌","何志行","Kevin","余涵睿","tiger"]
list1.append("胡老师")
print(list1)
  • extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'manni'];
aList.extend(bList)
print(aList)
  • insert() 函数用于将指定对象插入列表的指定位置。必须要有位置。
aList = [123, 'xyz', 'zara', 'abc', 123];
aList.insert(0,"积分")
print(aList)

  • 可以使用 del 语句来删除列表的的元素
list1 = ['Google', 'Runoob', 1997, 2000]
print(list1)
del list1[0]#在原来的列表中删除
print(list1)
  • pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
aList = [123, 'xyz', 'zara', 'abc', 123];
aList.pop(0)
print(aList)
  • remove() 函数用于移除列表中某个值的第一个匹配项。
aList = [123, 'xyz', 'zara', 'abc', 123];
aList.remove(123)
print(aList)

  • 使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示:
list1 = ['Google', 'Runoob', 1997, 2000]
print(list1[1])
print(list1[1:3])
print(list1[-2])#从右侧开始读取倒数第二个元素: count from the right
print(list1[1:])#   输出从第二个元素开始后的所有元素
  • 查看列表长度
list1 = ['Google', 'Runoob', 1997, 2000]
print(len(list1))
  • 返回列表元素最大值\最小值( 比较数字)
list2 = [1,2,3]
print(min(list2))
print(max(list2))
  • 元素是否在列表中(返回bool值)
list2 = [1,2,3]
print(1 in list2)
  • 迭代(查看每一个元素)
list1 = ['Google', 'Runoob', 1997, 2000]
for a in list1:
    print(a)
  • count() 方法用于统计某个元素在列表中出现的次数。
list1 = ['Google', 'Runoob', 1997, 2000,2000,2000]
print(list1.count(2000))
  • index() 函数用于从列表中找出某个值第一个匹配项的索引位置。
aList = [123, 'xyz', 'zara', 'abc', 123];
num = aList.index(123)
print(num)

  • 你可以对列表的数据项进行修改或更新
list1 = ['Google', 'Runoob', 1997, 2000]
print(list1[1])
list1[1] = "周杰伦"#把第二个元素修改了
print(list1[1])

列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。

  • 组合列表
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1,2,3]
print(list1 + list2)
  • 重复
list2 = [1,2,3]
print(list2*3)

相关文章

网友评论

      本文标题:2018-10-10列表

      本文链接:https://www.haomeiwen.com/subject/aiwpaftx.html