1. List of Numbers to List of Strings
For example, we have this object:
Array and in Python it's a
And for some reason, we need to convert every member into
String. As you can see above, every member is a number (integer).
We can use the new method
map() to do that. Basic looping method using
do - while can also do the task.
But of course, because
map() is designed to be sweeter than the basic methods, let's use it.
b now consists of all members of variable
a, but each of them is now a string.
Use your browser console, and copy paste the code above. And then put
console.log(b); to see its content.
In Python, when we design some structure which needs the conversion for some other process, we can use this shorthand:
Well, not really.
You can use Python interpreter (command line) to
b (the result).
It will have the same members as variable
a, but every (number) member is converted into a string.
To make it "safer", use this other shorthand to substitute the
b variable method:
str()is to convert anything to string.
vis each member of variable
ais the input variable (list) we wanna convert.
- And the square brackets,
[...], are to initiate a
2. The Other Way Round
For instance, we wanna extract the number only from an array which has that.
Let's use this object example:
It has string and number. Let's implement again the
b now is the number part of every variable
toString()method is needed so when the method meets a non-string element, particularly the
matchmethod, it will have no problem for searching using
RegExpsearcher, with the
\dis the shorthand for digit (number). We can also use
The plus sign
+is for pattern search for number that has 1 digit length or more.
gflag is for searching globally within the string.
- And the
match()method means that we're only interested in the first finding[?] (index 0).
match()method produces array of found patterns.
Let's use the same input. And activate Python power.
On the above example, the list is converted into string, by using
findall() transformed that string into list (of found patterns). And then the string to number (integer) mapping begins -- the
But, for scattered around number, e.g. the number patterns for each member is separated by non-digit, and we just wanna take the first found number pattern (index 0), we can substitute the method for variable
b into this:
Whichever the most proper one.
But, if we time the execution using
timeit module, the
map() shorthand is faster than the second one. The populating list using that
for in method. The third snippet is the slowest, since it's just the second one but then it's mapped. Like, seriously.
I'll be going now. Thanks for visiting.