Like this:
numrows = len(input) # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example
Assuming that all the sublists have the same length (that is, it's not a jagged array).
Answer from Óscar López on Stack OverflowLike this:
numrows = len(input) # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example
Assuming that all the sublists have the same length (that is, it's not a jagged array).
You can use numpy.shape.
import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])
Result:
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.shape(x)
(3, 2)
First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.
Videos
for i in range(height):
for j in range(width):
array[i][j] = charI puted the values in the array like this
but I dont konw how to do like this (I want to know length of "i" and "j")
array[i][j] len(i) , len(j)
length = sum([len(arr) for arr in mylist])
sum([len(arr) for arr in mylist[0:3]]) = 9
sum([len(arr) for arr in mylist[1:3]]) = 6
sum([len(arr) for arr in mylist[2:3]]) = 3
Sum the length of each list in mylist to get the length of all elements.
This will only work correctly if the list is 2D. If some elements of mylist are not lists, who knows what will happen...
Additionally, you could bind this to a function:
len2 = lambda l: sum([len(x) for x in l])
len2(mylist[0:3]) = 9
len2(mylist[1:3]) = 6
len2(mylist[2:3]) = 3
You can flatten the list, then call len on it:
>>> mylist=[[1,2,3],[4,5,6],[7,8,9]]
>>> import collections
>>> def flatten(l):
... for el in l:
... if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
... for sub in flatten(el):
... yield sub
... else:
... yield el
...
>>> len(list(flatten(mylist)))
9
>>> len(list(flatten(mylist[1:3])))
6
>>> len(list(flatten(mylist[0:1])))
3
I am using two for loops, on the inside of the second loop I want to create a 2d array that adds a new row once the second loop is finished. Is it possible to do something like this in Python?
Desired[i,j] = thing.thing(j) I’m trying to add to the array to make it bigger with each iteration.
Hello!
I have 5 sets, each set contains a number of elements of variable length (eg. set 1 has 100 elements, set 2 has 150 and so on)
Is it possible to store these sets in a single structure?
For example, if I want to print the 35th elements of the 3rd set, I could call it simply by saying something like MyContainer[setN][elementN]
I was trying to use a 2D array but I can't initialize its shape, since each set has a variable number of elements.
Can anybody point me to the right direction / best practice?
Thank you