Get the App
SLTechnology News&Howtos  ›  Development  › 

How Python converts numbers into lists

Shulou Source: shulou.com Published: 2022-06-02 16:13:35 09月25日 Update

Editor to share with you how Python converts numbers into lists. I hope you will get something after reading this article. Let's discuss it together.

1. Digitizedef digitize (n): return list (map (int, str (n)) # EXAMPLESdigitize (123) # [1,2,3]

The body logic of this function is to convert the input number into a string, then use the map function to convert the string into int type in order, and finally convert it to list.

Why do the numbers you enter get a list after this conversion? This is because str in Python is an iterable type. So str can use the map function, while map returns an iterator, which is also an iterative type. Finally, use this iterator to build a list.

2. Python determines whether the object can be iterated.

At present, the common method of judgment on the network is to use the Iterable type of the module of collections.abc (which was part of collections before 3.3.3).

From collections.abc import Iterableisinstance ('abc', Iterable) # Trueisinstance (map (int,a), Iterable) # True

Although there is no problem using this in the current scenario, according to the official documentation, the only reliable way to detect whether an object is an iterable is to call iter (obj).

Class collections.abc.Iterable

ABC for classes that provide the _ iter__ () method.

Checking isinstance (obj, Iterable) detects classes that are registered as Iterable or that have an _ iter__ () method, but it does not detect classes that iterate with the _ getitem__ () method. The only reliable way to determine whether an object is iterable is to call iter (obj).

> iter ('abc') after reading this article, I believe you have a certain understanding of "how Python converts numbers into lists". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!

Tags: Iterations numbers types functions characters strings objects methods modules articles input body trust at the same time scenarios dead official common documentation more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology NVidia OPPO Reno Xiaomi Shulou Tech Info