I just started using Python for this project I was working on. I created a List of lists of lists of integers.
Ex. [[[0,1,2],[0,2,1]],[[0,1,2],[2,1,0]],[[0,1,2],[1,0,2]]]. I want to make all possible arrays that take one list from each list in the large list and map the integers to the corresponding columns on the 2d array. How can I do that without nested for loops? I would have used for loops for each list of lists, but the lengths of the list aren't fixed. The list follows this pattern.
list ((l[i])[(i-1)!])[i]
ex of final matrix.
[0 2 1]
[2 1 0]
[1 0 2]
This is the code I have so far:
k = (range(len(m)))
q = list(permutations(k))
p = list
for e in range(0, len(m)):
p.extend(q)
for j in range(0, len(m)):
if ((p[e])[j])[e] != e:
p[e].pop(j)
for z in range(0, len(m)):
Where m is the array I want to create (len(m) x len(m) array)
Thanks in advance.
Related
I want that user give input like this
[[3,4,5],[7,2,1]]
and it will create a 2d array automatically and store in a. so when print(a) will given it returns
a=[[3,4,5],[7,2,1]]
where type(a[0][0]) i mean all elements inside a will be int. How can I do it?
Input:
2 // no.of rows
3 // no.of columns
1 2 3
4 5 6
Output:
[[1,2,3],[4,5,6]]
Solution:
r = int(input())
c = int(input())
a = [list(map(int,input().split())) for _ in range(r)]
print(a)
The variable c isn't used in the code, so you can simply get it as a string and also ignore the assignment using input()
Line 3 involves List Comprehension (documentation).
n = int(input())
m = int(input())
input_list = []
for i in range(n):
list1 = []
for j in range(m):
z = int(input())
list1.append(z)
input_list.append(list1)
print(input_list)
Okay so we take the size of the 2-d array from the user in n and m resp.
We create an empty list named as input_list.
Now we run a loop for n times so this will be the number of rows in the 2-d array.
for every row we create a list named as list1. Run a loop to take inputs from the user on the elements in the row.
Then we append the newly created row (list1) in the input_list.This action is performed for all the rows.
And when the execution finishes we get the input_list as a 2-d array.
#create a simple list in python
#list comprehension
x = [i for i in range(100)]
print (x)
#using loops
squares = []
for x in range(10):
squares.append(x**2)
print (squares)
multiples = k*[z for z in x] for k in squares
So in the last line of code I am trying to multiply both the lists. the problem is the lists are not of the same side and k*[z for z in x] this part is also incorrect.
For problems with iteration, I suggest anyone to check Loop Like A Native by Ned Batchelder and Looping like a Pro by David Baumgold
Option 1
If you want to multiply them as far as the shortest list goes, zip is your friend:
multiples = [a * b for a, b in zip (x, squares)]
Option 2
If you want a matrix with the product, then you can do it like this
result = [
[a * b for a in x]
for b in squares
]
I don't quite understand what the desired output would be. As the function stands now, you would have a list of lists, where the first element has 100 elements, the second one 400, the third 900, and so on.
One thing that's strange: The expression [z for z in x] defines a list that is identical to x. So, you might just write k*x
If you want to multiply the elements of both lists, you would have to write [[k*z for z in x] for k in squares]. This would lead to a list of 10 lists of 100 elements (or a 10x100-matrix) containing the products of your lists.
If you want to have one list of length 100 in the end that holds some kind of products, you will have to think about how to proceed with the shorter list.
EDIT: Or if you want to multiply them as far as possible until you reach the end of the shorter list, FRANCOIS CYRIL's solution is an elegant way to do so.
You can loop on each array to multiply element by element at the same position in a result array:
i = 0
arrayRes = []
while i < min (len(array1),len(array2)):
arrayRes.append(array1[i]*array2[i])
i+=1
Or do you prefer to multiply them, matrix way?
x = 0
y = 0
arrayRes = []
while x < len(array1):
arrayRes.append([])
while y < len(array2):
arrayRes[x].append(array1[x]*array2[y])
y+=1
x+=1
i do learn Python for scientific working. At the moment i try to generate a 10x10 random Matrix with binary entries: 0 and 1. I already got a solution with numpy BUT im interested of what is the error in my own solution.
The Idea is to Access every entry of my Matrix seperately and assign a value to it by calling random.randint(0, 1 ) within two while loops. In Advance i define a dummy 10x10 Matrix called "World" and reassign ist values it in the loop. The Code Looks how follows:
import random
World=list(10*[10*[0]]) #this is my dummy matrix
i=0
j=0
while i <= 9:
while j <= 9:
World[i][j]=random.randint(0, 1) #here i want to Access a specific element of my dummy Matrix and "overwrite" it
if j == 9:
j=0 #if the counter "j" reaches 9 - the last element - it shall assign j=0 and leave the innermost while loop by "break"
break
j=j+1
i=i+1
for x in World:
print(*x)
The Problem with the Output should be obvious:
columns are equal
I am hopefully u understand what was my Intention here and can help me fix my code. I tried many many Things but i did not fix this.
I already found a 2-line short solution which i will use in my final Code but i want to run this also on my own because i am convinced this could work also well.
Many Thanks in Advance.
- Wendel
Your error is in the creation of the list.
NOTE:
[0] * m returns just a reference to a list of m zeros, but not a list.
The subsequent repeating of this element creates a list of n items
that all reference to the same list (just as well as the operation b =
a for lists does not create the new list), so all rows in the
resulting list are actually the same string.
import random
#World=list(10*[10*[0]]) #this is my dummy matrix
n = 10
World= [0] * n
for i in range(n):
World[i] = [0] * n
i=0
j=0
while i <= 9:
while j <= 9:
World[i][j]=random.randint(0, 1) #here i want to Access a specific element of my dummy Matrix and "overwrite" it
if j == 9:
j=0 #if the counter "j" reaches 9 - the last element - it shall assign j=0 and leave the innermost while loop by "break"
break
j=j+1
i=i+1
for x in World:
print(*x)
Suppose that two numbers are given: the number of rows of n and the number of columns m. You must create a list of size n×m, filled with, say, zeros.
The obvious solution appears to be wrong:
a = [[0] * m] * n
This can be easily seen if you set the value of a[0][0] to 5, and then print the value of a[1][0] — it will also be equal to 5. The reason is, [0] * m returns just a reference to a list of m zeros, but not a list. The subsequent repeating of this element creates a list of n items that all reference to the same list (just as well as the operation b = a for lists does not create the new list), so all rows in the resulting list are actually the same string.
n = 3
m = 4
a = [[0] * m] * n
a[0][0] = 5
print(a[1][0])
A possible way: you can create a list of n elements (say, of n zeros) and then make each of the elements a link to another one-dimensional list of m elements:
n = 3
m = 4
a = [0] * n
for i in range(n):
a[i] = [0] * m
Another (but similar) way: create an empty list and then append a new element to it n times (this element should be a list of length m):
n = 3
m = 4
a = []
for i in range(n):
a.append([0] * m)
But the easiest way is to use generator, creating a list of n elements, each of which is a list of m zeros:
n = 3
m = 4
a = [[0] * m for i in range(n)]
In this case each element is created independently from the others. The list [0] * m is n times consructed as the new one, and no copying of references occurs.
I have an empty matrix in Python 2.7:
self.board = {}
N = 2
for i in range(N):
for j in range(N):
self.board[i, j] = 0
Now I want to add up all elements of the matrix. So I googled how to do it:
print sum(map(sum, self.board))
How would I sum a multi-dimensional array in the most succinct python?
Suprisingly, it prints out 4 - the sum of all indexes. Why is that? How can I sum the elements correctly?
I have a vector with int values like:
v=[10,8,6]
and what I want is to create an m*m matrix that stores the distance between these elements, i.e. take each element of the vector and substract it from all the other ones, so at the end I will end up with:
m[3][3]=10-10 10-8 10-6
8-10 8-8 8-6
6-10 6-8 6-6
I want to implement it into Python, but without using NumPy. I have done this so far:
def main():
v=[10,8,6]
l=len(v)
m=[]
#filling the matrix
for i in range(0,l-1):
for j in range(0,l-1):
m[i][j]=abs(v[i]-v[j])
#visualize the matrix
for i in range(0,l-1):
for j in range(0,l-1):
print m[i][j]
But I am getting some error that does not recognize with the bounds of m. Why is that?
v= [10,8,6]
m = [[abs(y-x) for y in v] for x in v]
EDIT:
For pretty printing you can use something like:
for i in m:
print '%s '*len(i) % tuple(i)
You need to make a list for each row inside of the enveloping list. I used a double list comprehension to make m and then made the formatting a little prettier for printing out the matrix. Also, watch your indices: remember that range goes from the first index to one minus the second index passed to it. You could also do print ' '.join(row) for each row in m to print it out nicely.
def main():
v=[10,8,6]
l=len(v)
#filling the matrix
m=[[abs(x - y) for y in v] for x in v]
#visualize the matrix
for i in range(0,l):
for j in range(0,l):
print m[i][j],
print
main()
result:
0 2 4
2 0 2
4 2 0
Your list starts out empty. You can't index the element in the list. One way to solve this would be to create the lists and then append them.
m=[]
#filling the matrix
for i in range(0,l-1):
x = []
for j in range(0,l-1):
x.append( abs(v[i]-v[j]) )
m.append(x)
Or you could create the matrix and then fill it up
m=[[0] *l for x in range(l)]
#filling the matrix
for i in range(0,l-1):
for j in range(0,l-1):
m[i][j]=abs(v[i]-v[j])
better yet is the list comprehension other have shown
m = [[abs(y-x) for y in v] for x in v]
but then, I'd use numpy/scipy
m = scipy.spatial.distance.pdist(v)
You need to initialize each object in the first dimension as an array, otherwise it's like you're basically trying to index on None.
#filling the matrix
for i in range(0,l-1):
m[i] = []
for j in range(0,l-1):
m[i][j]=abs(v[i]-v[j])