Python3 - list

Sequence, the data structure comprising a number of data, arranged in the order, in which data is accessed by an index. Python common sequence types are strings, lists and tuples.

List, save the object container, you can store any data type. All elements in [], and each element divided by commas.

The list is variable. If a container is variable, it is possible to modify the objects in the container. The index of an element in the list is assigned a new object, you can change the element.

If each element may be used to iterate object, then the object can be iterative, the iteration is referred to as objects, strings, lists and tuples are available iterations. Iterative objects Each element has an index that represents the position of elements in the digital object may be iterative. Positive sequence index list starts from 0, the inverted index starting at -1.

Create an empty list

>>> list0 = []
>>> list0, type(list0)
([], <class 'list'>)

Elements of inquiry
1. queries through the index to a list of elements, slice ([start Index: step: end index]) follow the principle of care regardless of the end of the first time the list.

>>> list0 = ['A', 'B', 'C', 'D', 1, 2, 3, 4]
>>> list0[0]  # 查单个元素 
'A'
>>> list0[1], list0[2]  # 查多个元素
('B', 'C')
>>> list0[0:4]  # 切片
['A', 'B', 'C', 'D']
>>> list0[::2]  # 步长
['A', 'C', 1, 3]
>>> list0[:]  # 开始索引和结束索引不写则查询全部元素
['A', 'B', 'C', 'D', 1, 2, 3, 4]
>>> list0[0:0]  # 开始索引和结束索引为 0 ,返回空列表。
[]

2.index () method
to search through the index elements, there is the element of the index value is returned query elements, then there is no error: ValueError.

>>> list0 = ['A', 'B', 'C', 'D', 1, 2, 3, 4]
>>> list0.index('A')
0
>>> list0[list0.index('D')]  # 查找结果返回元素的值:先找索引,在通过索引找元素的值。
'D'
>>> list0.index('E')
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    list0.index('E')
ValueError: 'E' is not in list

Modify elements
to modify the value of the element through the index.
Note: When you modify the index is to first slice sliced to match the elements to remove, inserting new elements, new elements but does not limit the number must be iterative.

>>> list0 = ['A', 'B', 'C', 'D', 1, 2, 3, 4]
>>> list0[0] = 'a'
>>> list0
['a', 'B', 'C', 'D', 1, 2, 3, 4]
>>> list0[1:4] = 'bcef'  # 新元素不限制个数
>>> list0
['a', 'b', 'c', 'e', 'f', 1, 2, 3, 4]

Updated: 2019-08-18

Guess you like

Origin www.cnblogs.com/lipandeng/p/11355289.html