Lists and tuples

In python, the most basic data structure is a sequence. Each element in the sequence has a number, either a position or an index. The index of the first element is 0, the index of the second element is 1, and so on. 0-based refers to an offset relative to the beginning of the sequence . Use a negative index to indicate the position of the element at the end of the sequence.

Sequence overview

There are three types of sequences in Python: lists, tuples, and strings.

The difference between lists and tuples is that lists can be modified, while tuples cannot. (Think about why some built-in functions return tuples.)

When writing your own programs, you can use lists instead of tuples in almost all cases. One exception is to use tuples as dictionary keys. (Dictionary keys are not allowed to be modified.)

Lists are denoted by square brackets:

>>> lilei = ['lilei', 18]

Sequences can also contain other sequences:

>>> lilei = ['lilei', 18]
>>> hanmeimei = ['hanmeimei', 13]
>>> jom = ['jom', 15]
>>> database = [lilei, hanmeimei, jom]
>>> database
[['lilei', 18], ['hanmeimei', 13], ['jom', 15]]

  PS: Python supports a basic concept of data structures called containers. A container is basically an object that can contain other objects. The two main types of containers are sequences (lists, elements) and maps (such as dictionaries). In a sequence, each element has a number, and in a map, each element has a name (key). There is a kind of container that is neither a sequence nor a map, it is a collection.

Generic sequence operations

  Several operations apply to all sequences, including indexing, slicing, adding, multiplying, and membership checking. In addition, there are built-in functions in Python that can be used to determine the length of a sequence and find the largest and smallest elements in a sequence.

 PS: There is an operation that is not discussed for the time being, iteration . Iterating over a sequence means performing a specific operation on each of its elements.

index

  All elements in the sequence are numbered - starting from 0 and increasing. You can use numbers to access individual elements like this:

 

>>> msg = 'hello '
>>> msg[0]
'h'

 

  When using negative indexing, Python will count from the right (ie, the last position of the element) to the left, so -1 is the position of the last element.

>>> msg[-1]
' '

 String literals (and other sequence literals) can be indexed directly without first assigning them to a variable. This is the same as assigning to a variable and then performing an indexing operation on the variable.

 

>>> 'hello'[1]
'e'

  If the function call returns a sequence, indexing can be performed directly on it. For example, if you were pointing to get the fourth digit of the year entered by the user, you could do something like this:

>>> fourth = input("Year: ")[3]
Year: 2018
>>> fourth
'8'

  

slice

  In addition to using indices to access elements, slices can also be used to access elements within ranges . To do this, use two indices, separated by colons:

>>> msg = 'https://www.baidu.com'
>>> msg[12:17]
'baidu'

  第一个索引包含的是第一个元素的编号,但第二个索引是切片后余下的第一个元素标号。

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[3:6]
[4, 5, 6]
>>> numbers[3:6][1]
5

  这貌似就出现一个问题,无法取出来最后一个元素。可以这样:

>>> numbers[7:0]

 步长

  执行切片操作的时候,可以显示或者隐式的指定起点和终点,如:

>>> msg = 'god is girl'
>>> msg[0:]
'god is girl'
>>> msg[:8]
'god is g'
>>> msg[:]   #复制整个序列
'god is girl'

  但通常忽略一个参数,即步长。在普通切片中,步长为1(即默认为1).可以显示的指定步长:

>>> msg[0::2]
'gdi il'

  还可以指定负数步长:

>>> msg[-1:0:-2] 'li id'

  序列相加

可使用加法运算符来拼接序列:

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'hello' + ' ' + 'world!'
'hello world!'
>>> [1, 2, 3] + 'hello'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

  PS:一般而言,不能拼接不同类型的序列。

相乘

将序列与数x相乘时,将重复这个序列x次来创建一个新序列:

>>> 'python' * 5
'pythonpythonpythonpythonpython'
>>> [1, 2] * 5
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

空列表:

>>> list = []
>>> list
[]

包含10个‘什么都没有的值’的列表 

>>> list = [None] * 10
>>> list
[None, None, None, None, None, None, None, None, None, None]  

 

 成员资格

要检查特定的值是否包含在序列中,可使用运算符in:

>>> name = 'Ubuntu'
>>> '0' in name
False
>>> 'u' in name
True
>>> list = ['root', 'ubuntu', 'admin']
>>> 'root' in list
True
>>> 'roo' in list
False

  一般而言,运算符in检查指定对象是否是序列(或其他集合)的成员(即其中的一个元素),但是对于字符串来说,只有它包含的字符才是其成员或元素。

 

函数list实则是类)

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

  可将任何序列作为list的参数。

>>> ''.join(['h', 'e', 'l', 'l', 'o'])
'hello'

修改列表

修改列表很容易,就如同普通的赋值,不同的是使用索引表示法给特定的元素赋值。

>>> x = [1, 2, 3, 4]
>>> x[1] = 1
>>> x
[1, 1, 3, 4]

PS:不能给部存在的元素赋值。

>>> x = [1, 2, 3, 4]
>>> x[4] = [5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

删除元素

从列表删除元素很容易,只需要使用del语句即可。

>>> list = ['root', 'ubuntu', 'admin']
>>> del list[0]
>>> list
['ubuntu', 'admin']

给切片赋值

>>> name = list('root')
>>> name
['r', 'o', 'o', 't']
>>> name[2:] = list('ubuntu')
>>> name
['r', 'o', 'u', 'b', 'u', 'n', 't', 'u']
>>> name[2:] = '0'
>>> name
['r', 'o', '0']

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326046127&siteId=291194637