- Convert map object to numpy array in python 3
- Convert map object to numpy array in python 3
- In javascript, create Array from an iterator [duplicate]
- How to create a map in javascript with array of values dynamically
- Create a mapping of elements from two arrays
- Map object python to array
- # Convert a Map object to a List in Python
- # Iterating over a Map object
- # Convert a Map object to a List using iterable unpacking
- # Using a list comprehension instead of the map() function
- # Convert a Map object to a List using a for loop
- # Using a for loop instead of the map function
- # Additional Resources
- Convert a Map Object Into a List in Python
- Use the list() Method to Convert a Map Object Into a List in Python
- Use the List Comprehension Method to Convert a Map Object to a List in Python
Convert map object to numpy array in python 3
Solution: Yes, you can create a dictionary with the key as the element of the first list and value as the element on the second list, by zipping the two lists together, and converting the output to a dictionary The output will be Note that if you have duplicate elements in but the corresponding elements in are different, the last element of will be picked in the mapping for the duplicate elements, e.g for and . the mapping will be , since is picked for duplicate element and is picked for duplicate element
Convert map object to numpy array in python 3
In Python 2 I could do the following:
import numpy as np f = lambda x: x**2 seq = map(f, xrange(5)) seq = np.array(seq) print seq # prints: [ 0 1 4 9 16]
In Python 3 it does not work anymore:
import numpy as np f = lambda x: x**2 seq = map(f, range(5)) seq = np.array(seq) print(seq) # prints:
How do I get the old behaviour (converting the map results to numpy array)?
Edit : As @jonrsharpe pointed out in his answer this could be fixed if I converted seq to a list first:
but I would prefer to avoid the extra call to list .
One more alternative, other than the valid solutions @jonrsharpe already pointed out is to use np.fromiter :
>>> import numpy as np >>> f = lambda x: x**2 >>> seq = map(f, range(5)) >>> np.fromiter(seq, dtype=np.int) array([ 0, 1, 4, 9, 16])
Although you refer to it as seq , the map object in Python 3 is not a sequence (it’s an iterator , see what’s new in Python 3). numpy.array needs a sequence so the len can be determined and the appropriate amount of memory reserved; it won’t consume an iterator. For example, the range object, which does support most sequence operations, can be passed directly;
seq = np.array(range(5)) print(seq) # prints: [0 1 2 3 4]
To restore the previous behaviour, as you’re aware, you can explicitly convert the map object back to a sequence (e.g. list or tuple):
seq = np.array(list(seq)) # should probably change the name!
However, as the documentation puts it:
a quick fix is to wrap map() in list() , e.g. list(map(. )) , but a better fix is often to use a list comprehension (especially when the original code uses lambda )
So another option would be:
Alternatively, actually use numpy from the start:
import numpy as np arr = np.arange(5) arr **= 2 print(arr) # prints [ 0 1 4 9 16] in 2.x and 3.x
Convert map object to numpy array in python 3, Although you refer to it as seq, the map object in Python 3 is not a sequence (it’s an iterator, see what’s new in Python 3). numpy.array needs a sequence so the len can be determined and the appropriate amount of memory reserved; it won’t consume an iterator. For example, the range object, which does support most sequence operations, can be passed directly; Code sample>>> import numpy as np>>> f = lambda x: x**2>>> seq = map(f, range(5))>>> np.fromiter(seq, dtype=np.int)array([ 0, 1, 4, 9, 16])Feedback
In javascript, create Array from an iterator [duplicate]
given an iterator , what’s the best way to create an Array ?
let map = new Map(); map.set( 'key1', 'data' ); map.set( 'key2', 'more data' ); . // now, wish to have an array of keys let arr = //??// map.keys() //??//
I could do something lame like
but there has to be a better way.
Array.from(map.keys()) // ['key1', 'key2']
The Array.from() method creates a new Array instance from an array-like or iterable object.
In, Browse other questions tagged javascript arrays iterator ecmascript-6 or ask your own question. The Overflow Blog A history of open-source licensing from a lawyer who helped blaze the trail
How to create a map in javascript with array of values dynamically
I have this requirement. Depending on the number of arguments passed in the function, I need to create that many entries in my map. Say I have a function myfunc1(a,b,c) , I need to have a map with the keys as «a»,»b» and «c» and I can have more than one values for each of the keys. But the problem is that I do not know beforehand, how many values will come for those keys. As and when the values come, I need to add them to the list of values corresponding to the matching key in the map. How do I do this in javascript? I have found static answers like below. But I want to do this dynamically. Can we use the push method ?
var map = <>; map["country1"] = ["state1", "state2"]; map["country2"] = ["state1", "state2"];
I think this is what you are asking. addValueToList will create array/list dynamically if the key is not present in the map.
//initially create the map without any key var map = <>; function addValueToList(key, value) < //if the list is already created for the "key", then uses it //else creates new list for the "key" to store multiple values in it. mapMap object python to array = mapMap object python to array || []; mapMap object python to array.push(value); >
You can use the arguments list to populate your object with key corresponding to the strings passed in as arguments. Then you can write another function to populate this map with data.
var createMap = function() < var map = <>; Array.prototype.slice.call(arguments).forEach(function ( arg ) < map[arg] = null; >); return map; >
So createMap(‘para1′, para2′, para3’) will return an object with 3 keys: para1, para2, para3. All having null as value. You can obviously replace null with a reference to the data you want the key to have, if you want to do it all in one function.
Node.js — how to create a map in javascript with array of, addValueToList will create array/list dynamically if the key is not present in the map. //initially create the map without any key var map = <>; …
Create a mapping of elements from two arrays
I have two arrays which are outputs of a clustering algorithm. Is there a possibility of an automatic way to find the associative mapping .
Consider two label arrays:
array1 = [0,0,1,2,3] array2 = [4,4,6,8,7]
Visually these look the same, but for a larger label set, I want to find a mapping like .
Does Python have any method to do this?
I have looked at sklearn metrics for similar solution, no luck yet. Any help would be appreciated.
Yes, you can create a dictionary with the key as the element of the first list and value as the element on the second list, by zipping the two lists together, and converting the output to a dictionary
array_1 = [0,0,1,2,3] array_2 = [4,4,6,8,7] #Zip the two lists together, and create a dictionary out of the zipped lists mapping = dict(zip(array_1, array_2)) print(mapping)
Note that if you have duplicate elements in array_1 but the corresponding elements in array_2 are different, the last element of array_2 will be picked in the mapping for the duplicate elements, e.g for [0,0,1,1] and [4,5,6,7] . the mapping will be , since 5 is picked for duplicate element 0 and 7 is picked for duplicate element 1
Create a mapping of elements from two arrays, 1 Answer. Yes, you can create a dictionary with the key as the element of the first list and value as the element on the second list, by zipping …
Map object python to array
Last updated: Feb 18, 2023
Reading time · 3 min
# Convert a Map object to a List in Python
Use the list() class to convert a map object to a list.
The list class takes an iterable (such as a map object) as an argument and returns a list object.
Copied!my_list = ['1.1', '2.2', '3.3'] new_list = list(map(float, my_list)) print(new_list) # 👉️ [1.1, 2.2, 3.3] print(type(new_list)) # 👉️
We passed a map object to the list() class to convert it to a list.
The list class takes an iterable and returns a list object.
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
# Iterating over a Map object
If you only need to iterate over the map object, use a basic for loop.
Copied!my_list = ['1.1', '2.2', '3.3'] map_obj = map(float, my_list) for item in map_obj: # 1.1 # 2.2 # 3.3 print(item)
The item variable gets set to the current map item on each iteration.
# Convert a Map object to a List using iterable unpacking
You can also use the * iterable unpacking operator to convert a map object to a list.
Copied!my_list = ['1.1', '2.2', '3.3'] new_list = [*map(float, my_list)] print(new_list) # 👉️ [1.1, 2.2, 3.3] print(type(new_list)) # 👉️
The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.
Copied!result = [*(1, 2), *(3, 4), *(5, 6)] print(result) # 👉️ [1, 2, 3, 4, 5, 6]
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
# Using a list comprehension instead of the map() function
An alternative approach would be to directly use a list comprehension.
Copied!my_list = ['1.1', '2.2', '3.3'] new_list = [float(i) for i in my_list] print(new_list) # 👉️ [1.1, 2.2, 3.3]
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
In the example, we explicitly pass each list item to the float() class instead of doing it implicitly as we did with the map() function.
# Convert a Map object to a List using a for loop
You can also use a for loop to convert a map object to a list.
Copied!my_list = ['1.1', '2.2', '3.3'] map_obj = map(float, my_list) new_list = [] for item in map_obj: new_list.append(item) print(new_list) # 👉️ [1.1, 2.2, 3.3]
We declared a new variable and initialized it to an empty list and used a for loop to iterate over the map object.
On each iteration, we append the current item to the new list.
# Using a for loop instead of the map function
You can also use a for loop as a replacement for the map function.
Copied!my_list = ['1.1', '2.2', '3.3'] new_list = [] for item in my_list: new_list.append(float(item)) print(new_list) # 👉️ [1.1, 2.2, 3.3]
We used a for loop to iterate over the list.
On each iteration, we convert the current item to a float and append the result to a new list.
As shown in the previous examples, the same can be achieved using a list comprehension or the map() function.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Convert a Map Object Into a List in Python
- Use the list() Method to Convert a Map Object Into a List in Python
- Use the List Comprehension Method to Convert a Map Object to a List in Python
- Use the Iterable Unpacking Operator * to Convert a Map Object Into a List in Python
Python provides a map() function, which you can utilize to apply a particular function to all the given elements in any specified iterable. This function returns an iterator itself as the output. It is also possible to convert map objects to the sequence objects like tuple and list by utilizing their own factory functions.
This tutorial will discuss and demonstrate the different methods you can use to convert a map object into a list in Python.
Use the list() Method to Convert a Map Object Into a List in Python
Lists are part of the four built-in datatypes provided in Python and can be utilized to stock several items in a single variable. Lists are ordered, changeable, and have a definite count.
The list() function is used to create a list object in Python. This method is used to convert a specific tuple into a list. The following code uses the list() method to convert a map object into a list in Python:
a = list(map(chr,[70,50,10,96])) print(a)
Numerous processes that operate or execute over the iterables return iterators themselves in Python 3; this simplifies the language even more. This also leads to a better and more efficient program run.
Use the List Comprehension Method to Convert a Map Object to a List in Python
The list comprehension method is a relatively shorter and very graceful way to create lists formed on the basis of given values of an already existing list. This method can be used in this case, along with a simple iteration to create a list from the map object.
The program below uses this method to convert a map object into a list in Python:
a = [chr(i) for i in [70,50,10,96]] print(a)