Reputation: 103
I have 2 lists of numbers: a and b. A is a list of node numbers with type integer and b is a list of X coordinates with type float64. I want to combine these 2 equal length arrays (N) into an Nx2 array that preserves the data types. I am using this array later on in some boolean tests, so I need the first column to be integers. I've been using:
nodeID = np.concatenate([[a],[b]]).T
but obviously this converts everything into floating point numbers.
Thanks!
Upvotes: 1
Views: 3161
Reputation: 1037
zip function is the simpliest way. The short example:
>>> a = [1, 2, 3, 4, 5]
>>> b = [1.1, 2.2, 3.3, 4.4, 5.5]
>>> zip(a,b)
[(1, 1.1), (2, 2.2), (3, 3.3), (4, 4.4), (5, 5.5)]
>>>
If you want to get a
from the zip(a,b)
, just write:
>>> [x[0] for x in zip(a, b)]
[1, 2, 3, 4, 5]
A good idea is to make dictionary from two lists:
>>> keys = [1,2,3,4,5]
>>> values = [1.1,2.2,3.3,4.4,5.5]
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{1: 1.1, 2: 2.2, 3: 3.3, 4: 4.4, 5: 5.5}
But be carefull, the order in the dictionary is not saved. Access to the data from the dictionary is very simple:
>>> dictionary.keys()
[1, 2, 3, 4, 5]
>>> dictionary.values()
[1.1, 2.2, 3.3, 4.4, 5.5]
>>> dictionary[1]
1.1
>>>
Upvotes: 0
Reputation: 1
I'm assuming because you mentioned a 2D list in the title that what you want a list like the one below, where each node and coord have their type preserved:
[[node1, coord1], [node2, coord2], ... ]
You can do this in three quick lines without any modules, preserving the type of each variable:
nodeID = []
for i, node in enumerate(a):
nodeID.append([node, b[i]])
Thus, you will have a 2D list. Each element in the 2D list will itself be another list containing a pair of a node and a coordinate. Since Python is so type-insensitive, the type of both your node and your coordinate will be preserved. You will access each pair with:
pair1 = nodeID[0]
pair2 = nodeID[1]
pairx = nodeID[x]
And their contents with:
node1 = nodeID[0[0]]
node2 = nodeID[1[0]]
coord1 = nodeID[0[1]]
coord2 = nodeID[1[1]]
Hopefully that helps. :-)
Upvotes: 0
Reputation: 2139
One way to achieve your goal is to use numpy
's dtype
as documented in http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html
>>> import numpy as np
>>> dt = np.dtype([('a', np.int64, 1), ('b', np.float64, 1)])
>>> a = np.array([1,2,3,4], dtype=np.int64)
>>> b = np.array([1.,2.,3.,4.], dtype=np.float64)
>>> ab = np.array(zip(a,b), dtype=dt)
>>> ab[:]['a']
array([1, 2, 3, 4])
>>> ab[:]['b']
array([ 1., 2., 3., 4.])
Upvotes: 3
Reputation: 11144
You can use zip() here. If you just compare the element of list a, then what is the problem here?
a =[1,2,3,4]
b =["Hello", "world", "fellow"]
x=zip(a,b)
print x
for a,b in x:
if a == someThing:
doSomething()
Upvotes: 0