jtr0009 - 1 year ago 79
Python Question

# make a list of matrices from a list of data

I have a hypothetical list of data from a .txt document

0 1 2
3 4 5
6 7 8
(value)

I want to make 2 lists of matricies like this

``````list 1            list 2
[0, 1, 2]         [[0],[1],[2]]
[3, 4, 5]         [[3],[4],[5]]
[6, 7, 8]         [[6],[7],[8]]
``````

Each item in list 1 must be able to give me a dot product when multiplying by a previously declared matrix.

``````new list 1
dot([0,1,2],mat)
dot([3,4,5],mat)
dot([6,7,8],mat)
``````

I have tried appending the 3 values from the .txt document into a list as a matrix (this was done within a for loop)

``````list1.append ([value[0], value[1], value[2]]
``````

but it didn't work. It gave me an error.

Any help is appreciated.

You may achieve it via list comprehension as:

``````>>> my_string = '0 1 2 3 4 5 6 7 8'
>>> row = 3
>>> my_list = my_string.split() # split the string based on space ' '

>>> list_1 = [my_list[i*3:(i*3)+row] for i in range(row)]
>>> list_1 # Output for example 1
[['0', '1', '2'],
['3', '4', '5'],
['6', '7', '8']]

>>> list_2 = [[[c] for c in my_list[i*3:(i*3)+row]] for i in range(row)]
>>> list_2 # Ouput for example 2
[[['0'], ['1'], ['2']],
[['3'], ['4'], ['5']],
[['6'], ['7'], ['8']]]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download