Sequence [(list), (tuple)], the mapping (dictionary), a collection (set)

1 Notes:

    Python built more sequences, such as a list (list) and the tuple (tuple), in fact, the string (string) is also a sequence.

>>> "Hello,world!"
>>> "Hello,world!"[0]
'H'
>>>"Hello,world!"[-1]
'!'

       Data structure . Data structure in some way (such as by number) combination of data elements (shown with characters as well as other data structures) set. In Python, the basic data structure of a sequence (sequence). Each element has a sequence number, i.e., the position or index, wherein the index of the first element is 0, the second element of the index 1, and so on. In some programming languages, from the beginning to the element number 1 in the sequence, but the zero sequence indicated relative to the start offset . It seems more natural, while back around to the end of the sequence, the sequence indicates the position at the end of the element with a negative index.

      Note Python supports the basic concept of a data structure, called the container (container). It may basically comprise a container to another object. The two main container is a sequence (such as lists and tuples) and maps (e.g. dictionary). In sequence, each element has a number, while in the map, each element has a name (also known as keys). One map is neither sequence nor a container, which is a collection (set).

2. What lists are?

    List is a series arrangement of elements in a certain order. You can create include all letters of the alphabet, numbers 0 to 9 or a list of all the names of family members; also anything that can be added to the list, there is no relationship between its elements. Given the list usually contains multiple elements to represent complex list specifies a name (such as letters, digits or names) is a good idea.

    In Python, square brackets ([]) to indicate the list by commas to separate its elements.

>>> strings['A','B','C']
>>> strings
['A','B','C']

3. The general method of operation sequence

   There are several operations for all sequences, including index , slice , adding , multiplying and membership check. Further, Python also provides some built-in functions, it may be used to determine the sequence length of the sequence and to identify maximum and minimum elements.

index:

   All the elements of a sequence is numbered - from 0 increments. You can use this number to access the various elements like the following:

>>> names = ["zhangsan","lisi"]
>>> print(names[1])
lisi

   Index (indexing). You can use the index to retrieve elements. This indexing method is applicable to all sequences. When you use a negative index, Python from the right (i.e., from the last element) left start number, so -1 position of the last element.

>>> names = ["zhangsan","lisi"]
>>> print(names[-])
lisi

   For string literal (and other literal sequence), it can be performed directly on its indexing operation, requiring them to be assigned to the variable. This is first assigned to a variable index and then perform operations on variables effect is the same.

>>> ["zhangsan","lisi"]
>>> ["zhangsan","lisi"][0]
'zhangsan'

    If the function returns a sequence can be directly executed its index operations. For example, if you just want to get the user to enter the year of the first four, you can do something like this:

>>> fourth = input('Year: ')[3]
Year: 2005
>>> fourth
'5'

slice:

   In addition to using the index to access a single element, but may also be used sliced (slicing) to access a particular range of elements inside. For this purpose, two indexes can be used, separated by a colon:

>>> tag = '<a href="http://www.python.org">Python web site</a>'
>>> tag[9:30]
'http://www.python.org'
>>> tag[32:-4]
'Python web site'

   As you can see, sliced ​​suitable for extracting part of the sequence, in which the number is very important: The first number is the index of the first element contained, but the second index is the number of the first element of the remaining slices. Consider the following example:

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

   In short, you provide two indexes to specify the boundaries of the slices, where the first index specified element included in the slice, but the second index of the specified elements are not included in the slices.

   Shorthand: Suppose you want to access the foregoing list of numbers in the last three elements, it is clear you can explicitly specify this.

>>> numbers[7:10]
[8, 9, 10]

   Here, the index 10 refers to the first 11 elements: it does not exist, but it is before the last reached position after a further element is located. do you understand? If you want to start counting at the end of the list, you can use negative indexes.

>>> numbers[-3:-1]
[8, 9]

   However, this seems unable to contain the last element. If you are using index 0, that is, to the position before the end of the list and then further in which the result will be?

>>> numbers[-3:0]
[]

   The result is not what you want. In fact after the element, slicing operation is performed, if the first element index of the specified index specified in the second (here, the penultimate element 3 located on the back of the element 1), the result is an empty sequence. Fortunately, you can use the shorthand: if the end of the sequence to the end of the slice, the second index may be omitted.

>>> numbers[-3:]
[8, 9, 10]

   Similarly, if the slice opening sequence starts, the first index may be omitted.

>>>> numbers[:3]
>[1, 2, 3]

   In fact, to copy the entire sequence can be two indexes are omitted.

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

Larger step sizes (slice):

   Performing slicing operation, you explicitly or implicitly specify the start and end, but the other parameters normally omitted, i.e. step. In general slice, the step size is 1. This means that from one element to the next element, slice includes all elements between the start and end points.

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

   In this example, another number specified. You probably guessed, this is explicitly specified step. If the specified step size to 1, will skip some elements. For example, the step size is 2, extracting one element from between the beginning and end of every other element.

>>> numbers[0:10:2]
[1, 3, 5, 7, 9]
numbers[3:6:3]
[4]

   Step size explicitly specified, the abbreviations may be used. For example, an extraction element 3, 4 can be provided simply step from every other sequence.

>>> numbers[::4]
[1, 5, 9]

   Of course, the step can not be 0, otherwise it can not move forward, but it can be negative, that is, from right to left to extract elements.

>>> numbers[8:3:-1]
[9, 8, 7, 6, 5]
>>> numbers[10:0:-2]
[10, 8, 6, 4, 2]
>>> numbers[0:10:-2]
[]
>>> numbers[::-2]
[10, 8, 6, 4, 2]
>>> numbers[5::-2]
[6, 4, 2]
>>> numbers[:5:-2]
[10, 8

   In this case, to correctly extract lot of thought. As you can see, the first index is still included, while the second index is not included. When the step is negative, the first index must be greater than the second index. It may be a bit confusing is that when you omit the start and end of the index, Python actually execute the correct operation: step is positive, it moves from the starting and ending points, while the step is negative, it from the end move the starting point.

Sequences are added:

   Addition operator can be used to splice sequence.

 

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'Hello,' + 'world!'
'Hello, world!'
>>> [1, 2, 3] + 'world!'
Traceback (innermost last):
 File "<pyshell>", line 1, in ?
    [1, 2, 3] + 'world!'
TypeError: can only concatenate list (not "string") to list

 

   从错误消息可知,不能拼接列表和字符串,虽然它们都是序列。一般而言,不能拼接不同类型的序列。

乘法:

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

>>> 'python' * 5
'pythonpythonpythonpythonpython'
>>> [42] * 10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

None、空列表和初始化:

   空列表是使用不包含任何内容的两个方括号([])表示的。如果要创建一个可包含10个元素的列表,但没有任何有用的内容,可像前面那样使用[42]*10。但更准确的做法是使用[0]*10,这将创建一个包含10个零的列表。然而,在有些情况下,你可能想使用表示“什么都没有”的值,如表示还没有在列表中添加任何内容。在这种情况下,可使用None。在Python中,None表示什么都没有。因此,要将列表的长度初始化为10,可像下面这样做:

 

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

 

成员资格:

   要检查特定的值是否包含在序列中,可使用运算符in。这个运算符与前面讨论的运算符(如乘法或加法运算符)稍有不同。它检查是否满足指定的条件,并返回相应的值:满足时返回True,不满足时返回False。这样的运算符称为布尔运算符,而前述真值称为布尔值

 

>>> permissions = 'rw'
>>> 'w' in permissions
True
>>> 'x' in permissions
False
>>> users = ['mlh', 'foo', 'bar']
>>> input('Enter your user name: ') in users
Enter your user name: mlh
True
>>> subject = '$$$ Get rich now!!! $$$'
>>> '$$$' in subject
True

 

长度、最小值和最大值:

   内置函数lenminmax很有用,其中函数len返回序列包含的元素个数,而minmax分别返回序列中最小和最大的元素。

 

>>> numbers = [100, 34, 678]
>>> len(numbers)
3
>>> max(numbers)
678
>>> min(numbers)
34
>>> max(2, 3)
3
>>> min(9, 3, 2, 5)
2

 

   基于前面的解释,这些代码应该很容易理解,但最后两个表达式可能例外。在这两个表达式中,调用maxmin时指定的实参并不是序列,而直接将数作为实参。

4 . Python的主力:列表(list)

   列表不同于元组和字符串的地方——列表是可变的,即可修改其内容。另外,列表有很多特有的方法

函数(list):

   鉴于不能像修改列表那样修改字符串,因此在有些情况下使用字符串来创建列表很有帮助。为此,可使用函数list(类)。

>>> list('Hello')
['H', 'e', 'l', 'l', 'o']

   将字符列表(如前述代码中的字符列表)转换为字符串,可使用下面的表达式:

''.join(somelist)
'''
' '.join(somelist):将字符列表连接成字符串。
将字符列表、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
'''
#:' '.join(somelist)将字符列表转换为字符串,前面' '里面设置连接符号  
print(''.join(list_string)) #没有连接符
print('$'.join("China"))  #连接符$

基本的列表操作:

   可对列表执行所有的标准序列操作,如索引、切片、拼接和相乘,但列表的有趣之处在于它是可以修改的。修改列表的方式:给元素赋值、删除元素、给切片赋值以及使用列表的方法。(请注意,并非所有列表方法都会修改列表。)

修改列表:给元素赋值

 

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

 

不能给不存在的元素赋值,因此如果列表的长度为2,就不能给索引为100的元素赋值。要这样做,列表的长度至少为101。可先对列表初始化(None)。

删除元素

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

>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl']

注意到Cecil彻底消失了,而列表的长度也从5变成了4。除用于删除列表元素外,del语句还可用于删除其他东西。(比如字典内,还有可以删除变量)

 

 

>>> name = "zhang"
>>> print(name)
zhang
>>> del name
>>> print(name) #将会报错

给切片赋值

切片是一项极其强大的功能,而能够给切片赋值让这项功能显得更加强大。

 

 

>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[2:] = list('ar')
>>> name
['P', 'e', 'a', 'r']

 

从上述代码可知,可同时给多个元素赋值。你可能认为,这有什么大不了的,分别给每个元素赋值不是一样的吗?确实如此,但通过使用切片赋值,可将切片替换为长度与其不同的序列。

 

>>> name = list('Perl')
>>> name[1:] = list('ython')
>>> name
['P', 'y', 't', 'h', 'o', 'n']

使用切片赋值还可在不替换原有元素的情况下插入新元素。

>>> numbers = [1, 5]
>>> numbers[1:1] = [2, 3, 4]
>>> numbers
[1, 2, 3, 4, 5]

在这里,我“替换”了一个空切片,相当于插入了一个序列。你可采取相反的措施来删除切片。

>>> numbers
[1, 2, 3, 4, 5]
>>> numbers[1:4] = []
>>> numbers
[1, 5]

del numbers[1:4]等效

列表方法:

方法是与对象(列表、数、字符串等)联系紧密的函数。通常,像下面这样调用方法:

 

object.method(arguments)

 

方法调用与函数调用很像,只是在方法名前加上了对象和句点。列表包含多个可用来查看或修改其内容的方法。

 

方法append用于将一个对象附加到列表末尾

>>> lst = [1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

不会返回修改后的新列表,而是直接修改旧列表

方法clear就地清空列表的内容

 

>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[]

 

这类似于切片赋值语句lst[:] = []

方法copy复制列表。前面说过,常规复制只是将另一个名称关联到列表

>>> a = [1, 2, 3]
>>> b = a
>>> b[1] = 4
>>> a
[1, 4, 3]

要让ab指向不同的列表,就必须将b关联到a的副本。

>>> a = [1, 2, 3]
>>> b = a.copy()
>>> b[1] = 4
>>> a
[1, 2, 3]

这类似于使用a[:]list(a),它们也都复制a

方法count计算指定的元素在列表中出现了多少次

>>> ['to', 'be', 'or', 'not', 'to', 'be'].count('to')
2
>>> x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1, 2])
1

方法extend让你能够同时将多个值附加到列表末尾,为此可将这些值组成的序列作为参数提供给方法extend。换而言之,你可使用一个列表来扩展另一个列表。

 

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]

 

这可能看起来类似于拼接,但存在一个重要差别,那就是将修改被扩展的序列(这里是a)。在常规拼接中,情况是返回一个全新的序列。

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3]

如你所见,拼接出来的列表与前一个示例扩展得到的列表完全相同,但在这里a并没有被修改。鉴于常规拼接必须使用ab的副本创建一个新列表,因此如果你要获得类似于下面的效果,拼接的效率将比extend低:

 

 

>>> a = a + b

 

另外,拼接操作并非就地执行的,即它不会修改原来的列表。要获得与extend相同的效果,可将列表赋给切片,如下所示:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a[len(a):] = b
>>> a
[1, 2, 3, 4, 5, 6]

这虽然可行,但可读性不是很高

方法index在列表中查找指定值第一次出现的索引。

 

>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>> knights.index('who')
4
>>> knights.index('herring')
Traceback (innermost last):
  File "<pyshell>", line 1, in ?
    knights.index('herring')
ValueError: list.index(x): x not in list

 

 

 

 

 

 

 

    

 

 

 

 

 

 

  

Guess you like

Origin www.cnblogs.com/iBoundary/p/11229369.html