How to create dynamic multidimensional list in python - python

I know there are a lot of questions like this one, but I haven't found my answer so far.
I am trying to dynamically fill a list with other lists, but I don't know why my code doesn't do what I want.
My code:
x = [1,2,3]
y = [4,5,6]
x.append(y)
print (x)
What I get:
[1,2,3[4,5,6]]
What I realy want:
[[1,2,3],[4,5,6]]
My goal would be, to dynamically add more dimensions arranged like this.
Can somebody tell me, what I'm doing wrong?
Thanks a lot.

In your example, x is a list containing three elements (integers).
With append, you add a new element. By appending y, you are adding a list as a fourth element (3 integers, one list).
If you want to create a list of lists, tread x and y as elements for that, and combine them in a list:
x = [1,2,3]
y = [4,5,6]
list_of_lists = [x,y]
list_of_lists will then be [[1, 2, 3], [4, 5, 6]].
You can add another list by appending them:
list_of_lists.append([7,8,9])
... which will result in list_of_lists being [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

What you want is create a list of lists. You can do:
x = [1,2,3]
y = [4,5,6]
l = [x,y]
print(l)
Actually, if you want to deal with multi-dimensional arrays, you should probably look at the numpy library (https://numpy.org/)

x = [1,2,3]
y=[22,33,9]
x=(x,y)
print (list(x))
>> [[1, 2, 3], [22, 33, 9]]
x=list(x) #Perform type conversion of the output 'x' to get in list type
x.append([13,32,12])#then append the data you want
print (x)
>> [[1, 2, 3], [22, 33, 9], [13, 32, 12]]

Related

Adding or subtracting elements within list of list component wise

How do I add elements of lists within a list component wise?
p=[[1,2,3],[1,0,-1]]
I have tried the following:
list(map(sum,zip(p[0],p[1])))
Will get me [2,2,2] which is what I need. But how to extend it for a variable number of lists? For example, p=[[1,2,3],[1,0,-1],[1,1,1]] should yield [3,3,3].
A solution I figured out is the following:
import pandas as pd
p=[[1,2,3],[1,0,-1],[1,1,1]]
list(pd.DataFrame(p).sum())
Is there a more "Pythonic" way to solve this problem?
Use * for unpack lists:
a = list(map(sum,zip(*p)))
print (a)
[3, 3, 3]
In numpy solution is similar like in pandas:
a = np.array(p).sum(axis=0).tolist()
print(a)
[3, 3, 3]
You can use * to unpack the list and sum to sum it up.
If you are uncomfortable with the map function you can do it like this:
p = [[1, 2, 3], [4, 5, 6], [-5,-7,-9]]
sum_list = [sum(elem) for elem in zip(*p)]
print(sum_list)

Separating sublist into multiple list and assigning dynamic list_name

I am trying to split a nested list into multiple lists and assign their name dynamically. Untill now, I tried the code below, but it only works when we have equal length sublists and we give them names manually.
sub_list = [[1,2,3],[4,5,5], [2,63,6]]
l1, l2, l3 = map(list, zip(*sub_list))
print(l1)
print(l2)
print(l3)
# Output
[1, 4, 2]
[2, 5, 63]
[3, 5, 6]
The approach above will fail when we have unequal length sublists such as (sub_list = [[1,2,3],[4,5], [2]]) and it does not give lists dynamic names.
I know it can be done by for loop, but I am not able to make list_name using a loop.
Any help will help me to reach more closure to my work
you could use zip_longest from itertools as follows:
sub_list = [[1,2,3],[4,5], [2]]
from itertools import zip_longest
l1, l2, l3 = map(list, zip_longest(*sub_list))
print(l1)
print(l2)
print(l3)
Output:
# [1, 4, 2]
# [2, 5, None]
# [3, None, None]
Answering the first question: If you don't want to give a manual name assing the map() to just one variable:
sub_list = [[1,2,3],[4,5,5], [2,63,6]]
rotated = map(list, zip(*sub_list))
for r in rotated:
print(r)
# Output
# [1, 4, 2]
# [2, 5, 63]
# [3, 5, 6]
Not completely sure what you want to accomplish, but I suggest you take a look at:
How to use itertools.zip_longest(): Python: zip-like function that pads to longest length? (You can filter out the Nones afterwards)
How to create dynamically named vars (although this is generally not the best thing to do): How do I create a variable number of variables?
The following code performs in both of your special cases:
There are no errors if some input lists are shorter than others
Names are procedurally/dynamically generated
def rotate_list_matrix(rows):
nrows = len(rows)
col_counts = map(lambda lyst: len(lyst), rows)
ncols = max(col_counts)
for ci in range(0, ncols): # column index
lyst = list()
list_name = "l" + str(ci + 1)
globals()[list_name] = lyst
for ri in range(0, nrows):
try:
lyst.append(rows[ri][ci])
except:
break
return
list_mata = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
list_matb = [[1, 2, 3],
[4, 5 ],
[7 ]]
rotate_list_matrix(list_matb)
print(l1)
print(l2)
print(l3)

outcome first list in 2 dimensional list

I have a 2 Dimensional list like that :
list = [[2, 3, 5], [1,2,3], [4,5,6], [8,9,10],[5,6,7]]
I can print the first value of every list with this:
[i[0] for i in list]
and outcome is:
list = [2, 1, 4, 8, 5]
but i want to have outcome like this :
list = [[2,3,5],[1,2,3],[4,5,6]]
my code is this :
new_list = []
for i in list:
row = 1
row_list = list[row]
new_list.append(row_list)
can anyone help me?
I am a bit confused what are you asking, but if I get i right try
print(list[1][1]) #print 2nd element in 2nd subset
print(list[0:3]) #print first 3 elements (in this case subsets) in the list
I hope it help.
To remove few object from list, you can use
list.remove(something) #remove element from list
or to create new list just use
l=list[0:3]
but i want to have outcome like this : list = [[2,3,5],[1,2,3],[4,5,6]]
This should do it:
list_subset = list[:3] # the first 3 elements in the list
you can slice your list like this:
n = 3 # if you have number of items you need
new_list = list[:n]
or:
n = 2 # if you have number of items you want to remove
new_list = list[:-n]
note that:
DO NOT use list as a name of a variable, list is a built-in in python.
Simple slicing can be used to skip last two rows like this:
list = [[2, 3, 5], [1,2,3], [4,5,6], [8,9,10],[5,6,7]]
print(list[:-2])
[[2, 3, 5], [1, 2, 3], [4, 5, 6]]

How to sum arrays within an array?

Basically i have array = [[1 2 3],[4 5 6]]
I want to sum the values within 1 array to get sum_array = [6,15].
I have tried sum(array) on my actual dataset and got random numbers.(not the anticipated output).
sum can only be performed on an element that is configured with __add__ to handle it. For a list it needs to be, in a loose sense single dimensioned. Hence you need to get the flattened list inside.
Using List comprehension.
>>> [sum(l) for l in array]
=> [6, 15]
Using map
>>> list( map(sum, array) )
=> [6, 15]
#driver values :
IN : array = [[1,2,3],[4,5,6]]
Apart from existing answers, you can also use map and sum together for a better and cleaner approach:
array = [[1, 2, 3],[4, 5, 6]]
sumArray = map(sum, array)
OUTPUT
>>> sumArray
[6, 15]
You can use sum(array) as you suggested, just make sure you're creating a list with the values returned by sum:
array = [[1, 2, 3], [4, 5, 6]]
sums = [sum(x) for x in array]
>> [6, 15]
Using list comprehension along with sum eases the above task.
a = [ [1,2,3] , [4,5,6] ]
sum_list = [ sum[elem] for elem in a ]
print(sum_list)
#Output [6,15]
The below approach is lengthy, but I feel it is easier to understand for the beginner
array = [ [1,2,3], [4,5,6] ]
sum_list = []
for elements in array:
elements_sum = 0
for elem in elements:
elements_sum = elements_sum + elem
sum_list.append(elements_sum)
print(sum_list)
#Output [6,15]
and if you want the full sum of the array of array
do that
print(sum(list(map(sum, array)))
this will give you 21

Sorting and grouping lists and sub lists with the same values in Python

I'm wondering can anyone help me with this problem, I feel so close yet so far.... I can't seem to get my head around this.
I have a list of 3D vectors (X,Y,Z) to be sorted by columns - many of the X values are the same.
# Example list (L)
L = [1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]
# Desired result
R = [[1,7,9], [1,12,9]], [[2,4,9], [2,0,10]],[[4,6,2], [4,12,6]], [5,7,1], [7,6,2], [9,9,1]
# Example calling individual columns (real values expected to be in the 10's)
R[0] = [[1,7,9], [1,12,9]] # A column 2 high
R[3] = [5,7,1] # A column 1 high
Working example on a single list
Using the Counter function in the collections module and with some much appreciated help on here, the following code can sort a single list:
from collections import Counter
N = [2,5,7,9,2,8,5,2,7,9]
C = Counter(N)
print [ [k,]*v for k,v in C.items()]
# Returns [[8], [9, 9], [2, 2, 2], [5, 5], [7, 7]]
I tried linking the Y and Z values back to newly grouped X vectors, however I ran into indexing issues, as the indices of X list changed.
Any help on this would be much appreciated, so far this is my attempt and the direction I'm exploring... (passing values into functions)
from collections import Counter
N = [1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]
def compareXvalues(VectorList):
global Grouped_X_Vectors
Xvectors = []
for i in xrange (len(VectorList)):
Xvectors.append(VectorList[i][0])
C = Counter(Xvectors)
Grouped_X_Vectors = [ [k,]*v for k,v in C.items()]
for i in xrange (len(Grouped_X_Vectors)):
#print Grouped_X_Vectors[i]
pass
print N
compareXvalues(N)
print Grouped_X_Vectors
Any feedback or help would be much appreciated, my brain is fried.
You can accumulate them by X value in a dictionary and then sort the results into a list. In my example I use a defaultdict since I want to call append on the items of the dictionary and this prevents me from needing to initialize a list for each value of X that I encounter.
>>> from collections import defaultdict
>>> L = [[1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]]
>>> d = defaultdict(list)
>>> for item in L:
d[item[0]].append(item)
>>> R = sorted(d[x] for x in d)
>>> R
[[[1, 7, 9], [1, 12, 9]], [[2, 4, 9], [2, 0, 10]], [[4, 6, 2], [4, 12, 6]], [[5, 7, 1]], [[7, 6, 2]], [[9, 9, 1]]]
I know this is a bit different from the path you were taking, but the dictionary fulfills the basic idea you had of "linking" your Y and Z values to your X value.

Categories

Resources