python基本数据结构

List

  • list1 = [‘Google’, ‘Runoob’, 1997, 2000]
  • list2 = [1, 2, 3, 4, 5 ]
  • list3 = [“a”, “b”, “c”, “d”]
  • list4 = [‘red’, ‘green’, ‘blue’,’yellow’, ‘white’, ‘black’]

从第二位开始(包含)截取到倒数第二位(不包含)

print (“list[1:-2]: “, list[1:-2])//左闭右开

列表比较
列表比较需要引入 operator 模块的 eq 方法

导入 operator 模块

import operator

a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a,b): ", operator.eq(a,b))
print("operator.eq(c,b): ", operator.eq(c,b))

把元组或者字符串转化成列表

list( seq )
seq – 要转换为列表的元组或字符串。

  • append() 方法用于在列表末尾添加新的对象。
  • list.append(obj)
  • count() 方法用于统计某个元素在列表中出现的次数。
  • list.count(obj)

extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

list.extend(seq)

seq – 元素列表,可以是列表、元组、集合、字典,若为字典,则仅会将键(key)作为元素依次添加至原列表的末尾。

index() 函数用于从列表中找出某个值第一个匹配项的索引位置。

list.index(x, start, end)

  • x– 查找的对象。
  • start– 可选,查找的起始位置。
  • end– 可选,查找的结束位置。

pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

list.pop([index=-1])
该方法返回从列表中移除的元素对象。

insert() 函数用于将指定对象插入列表的指定位置。

  • list.insert(index, obj)
  • list.remove(obj)
  • list.reverse()
  • list.sort( key=None, reverse=False)

降序

vowels.sort(reverse=True)

获取列表的第二个元素

def takeSecond(elem):
return elem[1]
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

指定第二个元素排序

random.sort(key=takeSecond)
list.clear()
list2 = list1.copy()

元组 字典 集合

元组的不可变指的是元组所指向的内存中的内容不可变。