arr = [
"xxyyyxxxx",
"xxxeeexxx",
"xwwwxxxxx",
]
I've seen code similar to this used to simulate 2 dimensional arrays in python by parsing the contents using for in row and for in col. Using this method what would be the easiest way to identify a specific "index" (or rather the location of a character within a certain string). If you don't have to modify the array and having to type out the entire array isn't an issue would there still be a better way to simulate a 2 dimensional array?
Strings are immutable sequences that can be indexed just like lists. So here,
arr[0][2]
Would take the string with index 0, and from that the character with index 2 -- "y". So that works.
Better ways to do it depends on what you need to do exactly. Real 2D arrays are available in Numpy.
to get the position of a specific character you could do a 2D loop like so
for i in range(len(arr)):
for j in range(len(arr[i])):
if arr[i][j]=="e":
print str(i), ", ", str(j)
Related
I have a little question about python Numpy. What I want to do is the following:
having two numpy arrays arr1 = [1,2,3] and arr2 = [3,4,5] I would like to obtain a new array arr3 = [[1,2,3],[3,4,5]], but in an iterative way. For a single instance, this is just obtained by typing arr3 = np.array([arr1,arr2]).
What I have instead, are several arrays e.g. [4,3,1 ..], [4,3,5, ...],[1,2,1,...] and I would like to end up with [[4,3,1 ..], [4,3,5, ...],[1,2,1,...]], potentally using a for loop. How should I do this?
EDIT:
Ok I'm trying to add more details to the overall problem. First, I have a list of strings list_strings=['A', 'B','C', 'D', ...]. I'm using a specific method to obtain informative numbers out of a single string, so for example I have method(list_strings[0]) = [1,2,3,...], and I can do this for each single string I have in the initial list.
What I would like to come up with is an iterative for loop to end up having all the numbers extracted from each string in turn in the way I've described at the beginning, i.e.a single array with all the numeric sub-arrays with information extracted from each string. Hope this makes more sense now, and sorry If I haven't explained correctly, I'm really new in programming and trying to figure out stuff.
Well if your strings are in a list, we want to put the arrays that result from calling method in a list as well. Python's list comprehension is a great way to achieve that.
list_strings = ['A', ...]
list_of_converted_strings = [method(item) for item in list_strings]
arr = np.array(list_of_converted_strings)
Numpy arrays are of fixed dimension i.e. for example a 2D numpy array of shape n X m will have n rows and m columns. If you want to convert a list of lists into a numpy array all the the sublists in the main list should be of same length. You cannot convert it into a numpy array if sublist are of varying size.
For example, below code will give an error
np.array([[1], [3,4]]])
so if all the sublist are of same size then you can use
np.array([method(x) for x in strings]])
Suppose I have a list of list called mat of shape 5x5.
Then I initialize a "column", element by element as follows
mat[0][4] = 'X'
mat[1][4] = 'O'
mat[2][4] = 'R'
mat[3][4] = 'N'
mat[4][4] = 'A'
Is there any way to initialize this column vector in one line in Python like how MATLAB might do?
mat[:,4] = ['X','O','R','N','A']
Not quite as concise, but:
for i,x in enumerate(['X','O','R','N','A']): mat[i][4]=x
Or in the case of single characters, slightly shorter:
for i,x in enumerate('XORNA'): mat[i][4]=x
Alternatively, you can use numpy:
import numpy
mat=numpy.array([[' ' for i in range(5)] for j in range(5)])
mat[:,4] = ['X','O','R','N','A']
I had a similar problem a couple of years ago while developing a Sudoku algorithm. I had to frequently switch between columns and rows and the nested "for" where killing me.
So I came up with the easy solution to just rotate my matrix and always treat everything as a row. If optimisation is not an issue, you can do that.
Here is how to rotate a multi-dimensional array in python: Rotating a two-dimensional array in Python
I'm new to python, but I'm solid in coding in vb.net. I'm trying to hold numerical values in a jagged array; to do this in vb.net I would do the following:
Dim jag(3)() as double
For I = 0 to 3
Redim jag(i)(length of this row)
End
Now, I know python doesn't use explicit declarations like this (maybe it can, but I don't know how!). I have tried something like this;
a(0) = someOtherArray
But that doesn't work - I get the error Can't assign to function call. Any advice on a smoother way to do this? I'd prefer to stay away from using a 2D matrix as the different elements of a (ie. a(0), a(1),...) are different lengths.
arr = [[]]
I'm not sure what you're trying to do, python lists is dynamically assigned, but if you want a predefined length and dimension use list comprehensions.
arr = [[0 for x in range(3)] for y in range(3)]
From Microsoft documentation:
A jagged array is an array whose elements are arrays. The elements of
a jagged array can be of different dimensions and sizes
Python documentation about Data Structures.
You could store a list inside another list or a dictionary that stores a list. Depending on how deep your arrays go, this might not be the best option.
numbersList = []
listofNumbers = [1,2,3]
secondListofNumbers = [4,5,6]
numbersList.append(listofNumbers)
numbersList.append(secondListofNumbers)
for number in numbersList:
print(number)
Which is the most performant way
to convert something like that
problem = [ [np.array([1,2,3]), np.array([4,5])],
[np.array([6,7,8]), np.array([9,10])]]
into
desired = np.array([[1,2,3,4,5],
[6,7,8,9,10]])
Unfortunately, the final number of columns and rows (and length of subarrays) is not known in advance, as the subarrays are read from a binary file, record by record.
How about this:
problem = [[np.array([1,2,3]), np.array([4,5])],
[np.array([6,7,8]), np.array([9,10])]]
print np.array([np.concatenate(x) for x in problem])
I think this:
print np.array([np.hstack(i) for i in problem])
Using your example, this runs in 0.00022s, wherease concatenate takes 0.00038s
You can also use apply_along_axis although this runs in 0.00024s:
print np.apply_along_axis(np.hstack, 1, problem)
In Numpy I have two three dimensional arrays representing images. I'm trying to create an overlay of the second image on to first so I'd like to replace all of the elements in the first array with respective elements from the second array but only when they aren't zero. Is there any easy way to do this?
This seems like a perfect use-case for np.where ...
new_arr = np.where(second == 0, first, second)
I've done the replacement out-of-place (creating a new array rather than modifying the original), but that's usually OK...
You can simply do:
zeros_idx = array2 != 0
array1[zeros_idx] = array2[zeros_idx]
Modifying the original using numpy.nonzero. Similar to answer provided by #Holt .
m = numpy.nonzero(array2)
array1[m] = array2[m]