Get the App
SLTechnology News&Howtos  ›  Development  › 

Introduction to the example usage of colons in Python

Shulou Source: shulou.com Published: 2022-06-03 16:54:10 10月04日 Update

This article introduces the knowledge of "introduction to the example usage of colons in Python". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Examples

A = [1, 2, 3, 4], [2, 3, 4, 5], [5, 6, 7, 8]]

B = np.array ([1, 2, 3, 4), [2, 3, 4, 5], [5, 6, 7, 8])

1. About [: J] or [: I]: this is a slicing operation, where elements before subscript I or j are retained, applicable to list (that is, arrays) in Python, as well as to numpy scientific structures (array, etc.).

The following is represented by list

# an is a list of Python (called array in data structure)

In [64]: a

Out [64]: [[1, 2, 3, 4], [2, 3, 4, 5], [5, 6, 7, 8]]

# example 1

In [65]: a [: 2]

Out [65]: [[1, 2, 3, 4], [2, 3, 4, 5]]

# example 2

In [66]: a [1] [: 3]

Out [66]: [2, 3, 4]

two。 About [:, j] or [:, I]: this is also a slicing operation, except that all the elements of the first dimension are retained and the second dimension elements are retained to j; only the scientific data structure of numpy is applicable.

Here is an example of using the data structure of numpy

# b is a numpy scientific data structure in array format

In [76]: b

Out [76]: array ([1,2,3,4]

[2, 3, 4, 5]

[5, 6, 7, 8])

# example 1

In [77]: b [:, 2]

Out [77]: array ([3,4,7])

# example 2

In [78]: b [:, 3]

Out [78]: array ([4,5,8])

# look at the negative example, if it is a list structure

In [6]: x

Out [6]: [[1, 2, 3, 4], [2, 3, 4, 5], [5, 6, 7, 8]]

In [5]: x [:,: 2]

TypeError Traceback (most recent call last)

In ()

-> 1 x [:,: 2]

TypeError: list indices must be integers or slices, not tuple

This is the end of the introduction to the example usage of colons in Python. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Examples structures data structures elements science colons examples content arrays more knowledge dimensions different practical successful learning and then that is the opposite dilemma Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology macOS Linux Apple Microsoft