Get the App
SLTechnology News&Howtos  ›  Development  › 

How python uses libraries

Shulou Source: shulou.com Published: 2022-06-01 04:24:35 11月02日 Update

Editor to share with you how to use python library, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Use the library

Just import the existing library and you can do what you really want to do.

Again, in the previous example, we build a function to count the number of times a number appears in the list. So, there is already a library that can do such a thing.

From collections import Counter bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] countr = Counter (bag) for i in range (10): print ("Count of {}: {}" .format (I, please [I]))

Some reasons for using the library:

The code is correct and tested.

Their algorithms may be optimal, so they can run faster.

Abstraction: they are clear and document-friendly, and you can focus on those that have not yet been implemented.

Finally, it's already there, and you don't have to recreate the wheels.

Slice / step in the list

You can specify start points and stop points, like this list [start:stop:step]. We take out the first five elements in the list:

Bag = [0,1,2,3,4,5,6,7,8,9] for elem in bag [: 5]: print (elem)

This is the slice. We specify that the stop point is 5, and before we stop, we will take five elements from the list.

What about the last five elements?

Bag = [0,1,2,3,4,5,6,7,8,9] for elem in bag [- 5:]: print (elem)

Don't you get it? -5 means taking five elements from the end of the list.

If you want to interval the elements in the list, you might do this:

Bag = [0,1,2,3,4,5,6,7,8,9] for index, elem in enumerate (bag): if index% 2 = 0: print (elem)

But here's what you should do:

Bag = [0 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag [:: 2]: print (elem) # or use rangesbag = list (range (0mem10)) print (bag)

This is the step in the list. List [:: 2] means traversing the list and fetching an element in two steps at the same time.

You can use list [::-1] to flip the cool list.

The above is all the contents of the article "how to use the Library for python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Elements articles content that is step by step not much not much things code examples functions just at the same time most meaning meaning pointing numbers documents more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Tech Info OPPO Reno MariaDB vpn