I also don't recommend this, but you could use a numpy.chararray for this:
import numpy as np
arr = np.chararray((100, 12, 31, 24, 60, 60), itemsize=100)
arr[52, 7, 12, 12, 44, 54] = 'year 1950+52, 7th month, 12th day, 12th hour, 44th minute, 54th second'
I'm not exactly sure what your desired structure is, but the string I inserted into the array should explain the structure I proposed, and you can change it however you need. Note that itemsize limits how many characters you can put in at any index.
Again, with a caveat that this is not necessarily the most efficient thing in the world to do, but if you wish to store lists of ints and/or floats in that array (as per your comment), one way to do it would be to convert that list to strings, and then when retrieving it, re-transform back to a list:
data_to_insert = [1,2,3,4.5]
# store as string
arr[52, 7, 12, 12, 44, 54] = ','.join(map(str, data_to_insert))
# retrieve
arr[52, 7, 12, 12, 44, 54].decode('utf-8').split(',')
This should be pretty fast
Answer from sacuL on Stack OverflowI also don't recommend this, but you could use a numpy.chararray for this:
import numpy as np
arr = np.chararray((100, 12, 31, 24, 60, 60), itemsize=100)
arr[52, 7, 12, 12, 44, 54] = 'year 1950+52, 7th month, 12th day, 12th hour, 44th minute, 54th second'
I'm not exactly sure what your desired structure is, but the string I inserted into the array should explain the structure I proposed, and you can change it however you need. Note that itemsize limits how many characters you can put in at any index.
Again, with a caveat that this is not necessarily the most efficient thing in the world to do, but if you wish to store lists of ints and/or floats in that array (as per your comment), one way to do it would be to convert that list to strings, and then when retrieving it, re-transform back to a list:
data_to_insert = [1,2,3,4.5]
# store as string
arr[52, 7, 12, 12, 44, 54] = ','.join(map(str, data_to_insert))
# retrieve
arr[52, 7, 12, 12, 44, 54].decode('utf-8').split(',')
This should be pretty fast
Though i won't recommend it, A multi dimentional empty list can be created by using list comprehension:
> >>> a = 4 #Width of elements
> >>> b = 6 #Width of main list container
>>>>> c = 4
>>>>> d = 3
> >>> l = [[[[0 for k in range(d) ] for z in range(c)] for x in range(a)] for y in range(b)]
> >>> [[[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]]]
Keep replacing 0 with list comprehensions to add more dimentions.
python - How can I create an empty 3d multidimensional array - Stack Overflow
python - how to create an empty 2 dimensional list based on another 2 dimensional list's length value? - Stack Overflow
Python 2.7 creating a multidimensional list - Stack Overflow
How can i create multidimensional list in Python? - Stack Overflow
def createList(l: list):
new_l = [[] for i in l]
return new_l
my_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9],[1],[]]
empty_2dimen_list = createList(my_list)
print(empty_2dimen_list)
>>> [[], [], [], [], []]
Use append instead of creating empty lists of lists:
empty_2dimen_list = []
for row in my_list:
empty_2dimen_list.append(' '.join([str(elem) for elem in row]))
or even list comprehension:
empty_2dimen_list = [' '.join([str(elem) for elem in row]) for row in my_list]
output:
['1 2 3 4', '5 6', '7 8 9', '1', '']
I think your list comprehension versions were very close to working. You don't need to do any list multiplication (which doesn't work with empty lists anyway). Here's a working version:
>>> y = [[[] for i in range(n)] for i in range(n)]
>>> print y
[[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []]]
looks like the most easiest way is as follows:
def create_empty_array_of_shape(shape):
if shape: return [create_empty_array_of_shape(shape[1:]) for i in xrange(shape[0])]
it's work for me
example code:
lst = [[]]
for x in a:
if x != '\n':
lst[-1].append(x)
else:
lst.append([])
print(lst)
output:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [3, 45, 6, 7, 2]]
Using itertools.groupby would do the job (grouping by not being a linefeed):
import itertools
a = [1,2,3,4,5,'\n',6,7,8,9,0,'\n',3,45,6,7,2]
new_list = [list(x) for k,x in itertools.groupby(a,key=lambda x : x!='\n') if k]
print(new_list)
We compare the key truth value to filter out the occurrences of \n
result:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [3, 45, 6, 7, 2]]
I'd suggest using np.full_like to choose the fill-value directly...
x = np.full_like((3, 1), None, dtype=object)
... of course the dtype you chose kind of defines what you mean by "empty"
I am guessing that by empty, you mean an array filled with zeros.
Use np.zeros() to create an array with zeros. np.empty() just allocates the array, so the numbers in there are garbage. It is provided as a way to even reduce the cost of setting the values to zero. But it is generally safer to use np.zeros().
You get the IndexError because you can't assign to an index in the list beyond the current length of the list. Since grid2 is initialized to an empty list, any attempt to index it will raise this error.
One correct way to write your nested list comprehension using for loops would be to construct the inner list first for each row, then append this to grid2:
grid2 = []
for i in range(rows):
inner = []
for j in range(cols):
inner.append(0)
grid2.append(inner)
you should initialize grid2=np.empty([rows, cols]) instead please refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html#numpy.empty for more details
New to python but not other higher level languages.
I’m having difficulty understanding how to use multidimensional lists in python.
I have a list if 256 objects. Each object has 6 variables. In other languages, I could read and update/change similar to
object[0] = [1,2,3,4,5,6]
…
object[255] = [1,2,3,4,5,6] Etc.
I understand in python this isn’t possible, so I’ll have to revert to something similar to
object = [[0], [1,2,3,4,5,6]]
…
object = [[255], [1,2,3,4,5,6]]
And reading will be similar to
var1 = object[0][3]
print(var1)
But I can’t get my head around it or find easy to,understand examples.
Does anyone have any quick and easy to digest resources that could help me understand this a bit better?
Thanks!
Hey guys,
I was wondering what was the best way to handle this. Example code as follows:
myArray = [[1],[2],[3],[],[5]]
for item in myArray:
try:
print(item[0])
except:
item[0] = 0
print(item[0])
So, the idea is to create an array which have one element which is empty. When encountered, Python returns an error (wrong index).
So I want to find a way to assign a value (empty string or 0 depending on specific case) when this error is encountered. However, the sample code above returns the same error. It's as if given index is invalid completely. Is there any workaround for this one?
Edit:
Fairly sure same is true for one-dimensional array. And I guess list, not array. Sorry :D
This has nothing to do with your specific use case, you make the beginner's mistake of assigning to the lowest non-existing index instead of using append. Assignment to an index (so list[n] = something) is only possible when there's already an item at that index.
myArray = [[1],[2],[3],[],[5]]
for item in myArray:
try:
print(item[0])
except IndexError:
item.append(0)
print(item[0])
Note that you should always except: the specific exception(s) you're expecting, don't use catch-all's (or if you do, print the actual exception). As when you let except: catch everything, then handle those using some silent operation, it will then also handle bugs silently causing frustration why the code works without error but returns incorrect results.
You're correct in your assumption that the index is invalid. In Python, Lists are dynamic arrays which means that they grow when elements get inserted into it, the memory won't necessarily be assigned up front like with an array. This means if you have an empty list (i.e. []) you won't be able to index into it at all, because there's nothing to index into, even for updating. To get the behaviour you want you will need to insert or append into the list so it knows to allocate memory for a new item e.g.
replace
item[0] = 0
with
item.append(0)
or
item.insert(0, 0)
Hope this helps.