2023/1/13python study notes (sequence)

Common characteristics of tuples, lists, and strings

Each element can be obtained by index

The index value of the first element is 0

You can obtain a collection of elements within a range through the slicing method.

There are many common operators

Therefore, lists, tuples, and strings are all called series

2Add the multiplication sign

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> "123" + "456"
'123456'
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> "123" * 3
'123123123'

3 About mutable and immutable

Variable series

>>> s = [1, 2, 3]
>>> id(s)
2285532322944
>>> s *= 2
>>> s
[1, 2, 3, 1, 2, 3]
>>> id(s)
2285532322944

immutable sequence

>>> t = (1, 2, 3)
>>> id(t)
2285532205952
>>> t *= 2
>>> t
(1, 2, 3, 1, 2, 3)
>>> id(t)
2285532393920

4 yes and no

Is (is) and is not (is not) are called identity operators and are used to detect whether the id values ​​between two objects are equal:

>>> x = "FishC"
>>> y = "FishC"
>>> x is y
True
>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x is not y
True

5Includes and excludes

The in operator is used to determine whether an element is included in the sequence, while not in is just the opposite:

>>> "Fish" in "FishC"
True
>>> "鱼" in "鱼C"
True
>>> "C" not in "FishC"
False

6del statement

The del statement is used to delete one or more specified objects:

>>> x = "FishC"
>>> y = [1, 2, 3]
>>> del x, y
>>> x
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    x
NameError: name 'x' is not defined
>>> y
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    y
NameError: name 'y' is not defined

7list(), tuple() and str()

list(), tuple() and str () These three BIF functions are mainly used to convert lists, tuples and strings.

8min() and max()

The function of the two functions min() and max() is to compare the parameters passed in and return the minimum and maximum values.

min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

The first one is passed in an iterable object

>>> s = [1, 1, 2, 3, 5]
>>> min(s)
1
>>> t = "FishC"
>>> max(t)
's'

This second type passes in multiple parameters and they will automatically find the minimum and maximum values ​​among them:

>>> min(1, 2, 3, 0, 6)
0
>>> max(1, 2, 3, 0, 6)
6

9len() and sum()

len() We have used the function many times before. There is no need to be verbose about its basic usage. Everyone understands it~ However, it has a maximum tolerable range, and some students may not know it yet. You know, like this

>>> len(range(2 ** 100))
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    len(range(2 ** 100))
OverflowError: Python int too large to convert to C ssize_t

This error is caused by the parameters of the len() function being too large. We know that Python is almost always implemented internally in the more efficient C language for execution efficiency.
In order to allow Python's own data structure to go through the back door, this len() function will directly read the length of the object in the C language structure.
Therefore, if the detected object exceeds a certain value, an error will occur.
Typically for 32-bit platforms, this maximum value is 2**31 - 1; for 64-bit platforms, this maximum value is 2**63 - 1.
The sum() function is used to calculate the sum of the items in the iteration object:

>>> s = [1, 0, 0, 8, 6]
>>> sum(s)
15

It has a start parameter, which is used to specify the starting value of the summation calculation. For example, here we set it to start adding from 100 :

>>> sum(s, start=100)
115

10sorted()和reversed()

The sorted() function will reorder the elements in the iterable parameter and return the result into a new liebiap:

>>> s = [1, 2, 3, 0, 6]
>>> sorted(s)
[0, 1, 2, 3, 6]

The sorted() function also supports key and reverse Two parameters, usage is consistent with the sort() method of the list:

>>> sorted(s, reverse=True)
[6, 3, 2, 1, 0]
>>> s.sort(reverse=True)
>>> s
[6, 3, 2, 1, 0]
>>> t = ["FishC", "Apple", "Book", "Banana", "Pen"]
>>> sorted(t)
['Apple', 'Banana', 'Book', 'FishC', 'Pen']
>>> sorted(t, key=len)
['Pen', 'Book', 'FishC', 'Apple', 'Banana']

sorted(t, key=len) This, because this key parameter specifies a function that interferes with the sorting algorithm.
For example, here we specify the len() function, then during the sorting process Python will first call the len() function once for each element in the list, and then compare len( ) results returned.
So, sorted(t, key=len) compares the length of each element.

The reverse() function will return an iterator of the parameters

>>> s = [1, 2, 5, 8, 0]
>>> reversed(s)
<list_reverseiterator object at 0x0000022926732AC0>

You see, it does not directly return the result of what you see is what you get, it returns a string of strange English...
As we just said, the result it returns is An iterator, and we can treat it as an iterable object.
In this case, we can use the list() function to convert it to a list:

>>> list(reversed(s))
[0, 8, 5, 2, 1]

The reversed() function also supports any form of iterable object:

>>> list(reversed("FishC"))
['C', 'h', 's', 'i', 'F']
>>> list(reversed((1, 2, 5, 9, 3)))
[3, 9, 5, 2, 1]
>>> list(reversed(range(0, 10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

11all() and any()

The all() function can determine whether all elements in the iterable object are true.

The any() function can determine whether there is an element in the iterable object.

>>> x = [1, 1, 0]
>>> y = [1, 1, 9]
>>> all(x)
False
>>> all(y)
Ture
>>> any(x)
True
>>> any(y)
True

12enumerate

The enumerate() function is used to return an enumeration object. Its function is to combine each element in the iterable object and the serial number starting from 0 to form a binary List of groups:

>>> seasons = ["Spring", "Summer", "Fall", "Winter"]
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

It has a start parameter, which can customize the starting value of the serial number:

>>> for i, j in enumerate(seasons, start=10):
...     print(i, "->", j)
... 
10 -> Spring
11 -> Summer
12 -> Fall
13 -> Winter

13zip()

This is done by combining each element of each iterable passed in as an argument into a tuple in turn, i.e. the i-th tuple contains the i-th element from each argument.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> z = [7, 8, 9]
>>> zipped = zip(x, y, z)
>>> list(zipped)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

One thing you need to pay attention to here is that if the lengths of the iterable objects passed in are inconsistent, the shortest one will prevail:

>>> z = "FishC"
>>> zipped = zip(x, y, z)
>>> list(zipped)
[(1, 4, 'F'), (2, 5, 'i'), (3, 6, 's')]

When we don’t care about the extra data in a long iterable object, using the zip() function is undoubtedly the best choice , as it automatically cuts off the excess.
However, if those values ​​make sense to us, we can use the itertools module  function instead:zip_longest()

>>> import itertools
>>> zipped = itertools.zip_longest(x, y, z)
>>> list(zipped)
[(1, 4, 'F'), (2, 5, 'i'), (3, 6, 's'), (None, None, 'h'), (None, None, 'C')]

14map()

The map() function will operate on each element of the specified iterable object according to the provided function, and will return an iterator of the operation result:

>>> mapped = map(ord, "FishC")
>>> list(mapped)
[70, 105, 115, 104, 67]

If the specified function requires two arguments, the number of following iterable objects should also be two:

>>> mapped = map(pow, [2, 3, 10], [5, 2, 3]))
>>> list(mapped)
[32, 9, 1000]

The above code is actually equivalent to:

>>> [pow(2, 5), pow(3, 2), pow(10, 3)]
[32, 9, 1000]

It can be seen that if the number is large, it is much more convenient to use the map() function.
If the length of the iterable objects is inconsistent, then Python takes the same approach as the zip() function, both in The shortest iterable ends when it terminates:

>>> list(map(max, [1, 3, 5], [2, 2, 2], [0, 3, 9, 8]))
[2, 3, 9]

15filter()

is similar to the map() function, filter() The function also needs to pass in a function as a parameter, but filter() The function is based on the provided function, for each element of the specified iterable object Perform an operation and return the element whose result is true in the form of an iterator:

>>> filter(str.islower, "FishC")
<filter object at 0x000001B5170FEFA0>

We passed in a string in the above code islower() method, its function is to determine whether the passed in parameters are lowercase letters. Combined with the filter() function, it can remove uppercase letters and retain lowercase letters.
If the function provided is None, it will be assumed to be a "authentication" function, that is, an iterable object All elements with a false value will be removed:

>>> list(filter(None, [True, False, 1, 0]))
[True, 1]

16 Iterators and Iterable Objects

The biggest difference is: we can perform repeated operations on iterable objects, while iterators are disposable!
Convert iterable object to iterator: iter() function.

>>> x = [1, 2, 3, 4, 5]
>>> y = iter(x)

Through the type() function, we can observe this difference:

>>> type(x)
<class 'list'>
>>> type(y)
<class 'list_iterator'>

Finally, there is a next() function in BIF, which is specifically for iterators.
Its function is to extract the elements in the iterator one by one:

>>> next(y)
1
>>> next(y)
2
>>> next(y)
3
>>> next(y)
4
>>> next(y)
5
>>> next(y)
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    next(y)
StopIteration

Now if you don't want it to throw an exception, you can pass it a second parameter:

>>> z = iter(x)
>>> next(z, "没啦,被你掏空啦~")
1
>>> next(z, "没啦,被你掏空啦~")
2
>>> next(z, "没啦,被你掏空啦~")
3
>>> next(z, "没啦,被你掏空啦~")
4
>>> next(z, "没啦,被你掏空啦~")
5
>>> next(z, "没啦,被你掏空啦~")
'没啦,被你掏空啦~'

Guess you like

Origin blog.csdn.net/qq_61134394/article/details/128678510