How to add zeroes to the end of a list and fill a matrix with it?
Currently I have
(1,0,1,1,0)
How to fill up a matrix such that it looks like this:
[[0, 0, 0],
[0, 1, 0],
[1, 1, 0]]
In your question, you have clearly added the zeroes to the beginning of the matrix rather than the end but whatever.
To extend a list to one with 9 items with preceeding zeroes:
list_out = [0]*(9-len(list_in)) + list_in
to extend a list to one with 9 items with trailing zeroes just reverse the order:
list_out = list_in + [0]*(9-len(list_in))
We can convert a list with 9 items to a matrix using
matrix = [li[0:3,li[3:6],li[6:9]
so eg.
list_in = [1,2,3]
li = list_in + [0]*(9-len(list_in))
matrix = [li[0:3],li[3:6],li[6:9]]
gives
[[1, 2, 3], [0, 0, 0], [0, 0, 0]]
Related
I am trying to create a 2D array as such and just update single values at a time, shown here:
M = [[0]*3]*3
M[0][0] = 3
print(M)
which is returning the following:
[[3, 0 , 0], [3, 0, 0], [3, 0, 0]]
Anyone have an idea of what I've done wrong?
What your first line is doing is creating one inner length 3 list, and adding three references of it to your outer list M. You must declare each internal list independently if you want them to be independent lists.
The following is different in that it creates 3 separate instances of inner length 3 lists:
M = [[0]*3 for _ in range(3)]
M[0][0] = 3
print(M)
OUTPUT
[[3, 0, 0], [0, 0, 0], [0, 0, 0]]
The 2D array is at the same address as the first array.
M = [[0,0,0],[0,0,0],[0,0,0]]
M[0][0] = 3
print(M)
Which is returning the following:
[[3, 0, 0], [0, 0, 0], [0, 0, 0]]
FYI: Problem same as this: Why in a 2D array a and *a point to same address?
I have an array "b" of size L^2 x L*(L+1), and an array "a" of size L x L.
currently my code is
for i in range (L):
for j in range (L):
b[i+j*L,i+j*(L+1)] = a[j,i]
What this means is that, for example for L=2, if the 2x2 array "a" has the form
ab
cd
then I want the 4x6 array "b" to be
a00000
0b0000
000c00
0000d0
How do I rewrite the same thing without using for loops?
What you want is to fill the diagonal of matrix B with the values of (flattened) A. Numpy has functions for this:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.html
https://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html
import numpy as np
# Set sample data
a = np.array([[1, 2], [3, 4]])
b = np.zeros([4,6])
# This is it:
np.fill_diagonal(b, a.flatten())
If you don't want to use a library, for example because this is a programming assignment, you can represent matrices as nested lists and use a list comprehension, as this:
# Prepare data
a = [[1, 2], [3, 4]]
L = len(a)
# "Build" the result
b = [[a[i//L][i%L] if i == j else 0 for j in range(L*(L+1))] for i in range(L*L)]
# Same, with better formatting:
b = [[a[i//L][i%L]
if i == j else 0
for j in range(L*(L+1))]
for i in range(L*L)]
# b will be = [[1, 0, 0, 0, 0, 0],
# [0, 2, 0, 0, 0, 0],
# [0, 0, 3, 0, 0, 0],
# [0, 0, 0, 4, 0, 0]]
Anyway you need to iterate through the items in 'a', so you are just replacing the 'for' constructions by a list comprehension. This might be more efficient for large matrices but arguably less clear.
Generalizing the answer from Milo:
L = (a.shape)[0]
b = np.zeros([L*L, L*(L+1)])
np.fill_diagonal(b, a.flatten())
This is probably a very basic question but I dont know what I have to search for to find the answer for it:
I have this code:
list = [[0,1],[0,2],[1,3],[1,4],[1,5]]
list.append(list[0])
for i in list:
i.append(0)
print(list)
This List will later be used as coordinates for a curve. I need to duplicate the first coordinate at the end to get a closed curve.
If I then want to add a third value to each coordinate in the list the first and last item in list will be iterated over twice:
[[0, 1, 0, 0], [0, 2, 0], [1, 3, 0], [1, 4, 0], [1, 5, 0], [0, 1, 0, 0]]
I am guessing they have the same memory address and thereby the append-function is applied to the same object at this address once for the first index and once for the last.
What is this phenomenon called ? what is the easiest way to get the list like this:
[[0, 1, 0], [0, 2, 0], [1, 3, 0], [1, 4, 0], [1, 5, 0], [0, 1, 0]]
Thank you for your help
You can do a list comprehension:
list = [[0,1],[0,2],[1,3],[1,4],[1,5]]
list.append(list[0])
list = [x + [0] for x in list]
print(list)
# [[0, 1, 0], [0, 2, 0], [1, 3, 0], [1, 4, 0], [1, 5, 0], [0, 1, 0]]
EDIT: The trick here is, using x + [0] within the list comprehension. This way new lists are created, thus you do not append 0 to the same list twice (Hattip to #dx_over_dt)
The problem you have with your approach is, that the first and last element of your list refers to the very same object. You can see this, when you print i and list for every iteration:
for i in list:
i.append(0)
print(i)
print(list)
So for the first and last i in your loop, you will append a 0 to the very same list.
You could stick to your approach appending a copy of the first element:
list.append(list[0].copy())
The simplest answer is to add the 0's before appending the closing point.
list = [[0,1],[0,2],[1,3],[1,4],[1,5]]
for i in list:
i.append(0)
list.append(list[0])
print(list)
It's the tiniest bit more efficient than a list comprehension because it's not making copies of the elements.
I have an 2D array:
2d_arr = [[a,b,c,d],[a,b],[c,d],[a,f]]
And another array:
arr = [a,w,b,x]
I want to compare every element in the 2D array (2d_arr) with the array (arr) and get the output as a new 2D array like this: (if the 2D array elements match the array put 1 else 0)
[a,w,b,x]
[1,0,1,0]
[1,0,1,0]
[0,0,0,0]
[1,0,0,0]
I have tried the follow:
for i in range(len(2d_arr)):
for j in range(len(2d_arr[i])):
if 2d_arr[i][j] == arr[i]
.....
I know the arr[i] from the last line is wrong but how would i iterate??
You can use a list comprehension:
arr_2d = [['a','b','c','d'],['a','b'],['c','d'],['a','f']]
arr = ['a','w','b','x']
[[int(x in a) for x in arr] for a in arr_2d]
[[1, 0, 1, 0], [1, 0, 1, 0], [0, 0, 0, 0], [1, 0, 0, 0]]
Create a two-dimensional array named A with ROWS rows and COLS columns. ROWS and COLSS are specified by the user at run time. Fill A with randomly-chosen integers from the range [ -10,99 ], then repeatedly perform the following steps until end-of-file(1) input an integer x(2) search for x in A(3) when x is found in A, output the coordinate (row,col) where x is found, otherwise output the message "x not found!"
I need help I am wondering how can we define two-dimensional array named A with ROWS rows and COLS columns. ROWS and COLSS are specified by the user at runtime in python latest version
#--------------------------------------
#Hw 7
#E80
#---------------------------------------
A = [[Rows],[ColSS]] #I really dont know how to defend this part
for i in range (-10,99): #dont worry about this its just the logic not the actual code
x = int(input("Enter a number : "))
if x is found in A
coordinate row and clumn
otherwise output "x is not found"
The idiomatic way to create a 2D array in Python is:
rows,cols = 5,10
A = [[0]*cols for _ in range(rows)]
Explanation:
>>> A = [0] * 5 # Multiplication on a list creates a new list with duplicated entries.
>>> A
[0, 0, 0, 0, 0]
>>> A = [[0] * 5 for _ in range(2)] # Create multiple lists, in a list, using a comprehension.
>>> A
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> A[0][0] = 1
>>> A
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Note you do not want to create duplicate lists of lists. It duplicates the list references so you have multiple references to the same list:
>>> A = [[0] * 5] * 2
>>> A
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> A[0][0] = 1
>>> A
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0]] # both rows changed!