Python四种基本数据结构之一——列表的简单使用(One of the four basic data structures in Python — simple use of lists)

列表(list)

list是一种有序集合,列表中的数据类型可以不一样。

  • 使用索引可以访问list每个位置的元素。索引从0开始,最后一个元素的索引是len(a)-1,如果要获取最后一个元素,还可以用-1做索引,-2是倒数第二个元素。
In [13]: a = ['A', 'B', 'C']

In [14]: a
Out[14]: ['A', 'B', 'C']

In [15]: a[0]
Out[15]: 'A'

In [16]: a[1]
Out[16]: 'B'

In [22]: a[-1]
Out[22]: 'C'

In [23]: a[-2]
Out[23]: 'B'

list是可变的有序表:

  • 往list末尾添加元素,append()方法
In [25]: a.append('D')

In [26]: a
Out[26]: ['A', 'B', 'C', 'D']
  • 向指定位置插入元素insert()方法
In [27]: a.insert(1, 'B1')

In [28]: a
Out[28]: ['A', 'B1', 'B', 'C', 'D']
  • 删除list末尾元素和删除指定位置的元素,pop()方法,该方法会返回pop的元素值。
In [31]: a
Out[31]: ['A', 'B', 'C', 'D']

In [32]: a.pop()
Out[32]: 'D'

In [33]: a.pop(1)
Out[33]: 'B'

In [34]: a
Out[34]: ['A', 'C']
  • 将某个元素替换成别的元素
In [38]: a
Out[38]: ['A', 'B', 'C', 'D']

In [39]: a[3] = 'E'

In [40]: a
Out[40]: ['A', 'B', 'C', 'E']
  • 元素可以是另一个list,获取列表中的列表的元素,可以看作二维数组
In [42]: s
Out[42]: ['a', 'b', ['c', 'd'], 'e']

In [43]: s[2][1]
Out[43]: 'd'
————————

List

< strong > list is an ordered set. The data types in the list can be different

  • Using an index, you can access the elements of each location in the list. The index starts from 0. The index of the last element is len (a) – 1. If you want to get the last element, you can also use – 1 as the index, and – 2 is the penultimate element.
In [13]: a = ['A', 'B', 'C']

In [14]: a
Out[14]: ['A', 'B', 'C']

In [15]: a[0]
Out[15]: 'A'

In [16]: a[1]
Out[16]: 'B'

In [22]: a[-1]
Out[22]: 'C'

In [23]: a[-2]
Out[23]: 'B'

List is a variable ordered table:

  • Add an element to the end of the list, and use the append () method
In [25]: a.append('D')

In [26]: a
Out[26]: ['A', 'B', 'C', 'D']
  • Inserts an element into the specified location using the insert() method
In [27]: a.insert(1, 'B1')

In [28]: a
Out[28]: ['A', 'B1', 'B', 'C', 'D']
  • Delete the element at the end of the list and the element at the specified position, pop () method, which will return the element value of pop.
In [31]: a
Out[31]: ['A', 'B', 'C', 'D']

In [32]: a.pop()
Out[32]: 'D'

In [33]: a.pop(1)
Out[33]: 'B'

In [34]: a
Out[34]: ['A', 'C']
  • Replace one element with another
In [38]: a
Out[38]: ['A', 'B', 'C', 'D']

In [39]: a[3] = 'E'

In [40]: a
Out[40]: ['A', 'B', 'C', 'E']
  • The element can be another list. The elements of the list in the list can be regarded as a two-dimensional array
In [42]: s
Out[42]: ['a', 'b', ['c', 'd'], 'e']

In [43]: s[2][1]
Out[43]: 'd'