Wrote this function in python that transposes a matrix:
def transpose(m):
height = len(m)
width = len(m[0])
return [ [ m[i][j] for i in range(0, height) ] for j in range(0, width) ]
In the process I realized I don't fully understand how single line nested for loops execute. Please help me understand by answering the following questions:
Given,
[ function(i,j) for i,j in object ]
Additional information is appreciated as well.
This question is related to
python
loops
for-loop
nested
nested-loops
You might be interested in itertools.product
, which returns an iterable yielding tuples of values from all the iterables you pass it. That is, itertools.product(A, B)
yields all values of the form (a, b)
, where the a
values come from A
and the b
values come from B
. For example:
import itertools
A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]
print [a + b for a, b in itertools.product(A, B)]
This prints:
[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]
Notice how the final argument passed to itertools.product
is the "inner" one. Generally, itertools.product(a0, a1, ... an)
is equal to [(i0, i1, ... in) for in in an for in-1 in an-1 ... for i0 in a0]
First of all, your first code doesn't use a for loop per se, but a list comprehension.
Would be equivalent to
for j in range(0, width): for i in range(0, height): m[i][j]
Much the same way, it generally nests like for loops, right to left. But list comprehension syntax is more complex.
I'm not sure what this question is asking
Any iterable object that yields iterable objects that yield exactly two objects (what a mouthful - i.e [(1,2),'ab']
would be valid )
The order in which the object yields upon iteration. i
goes to the first yield, j
the second.
Yes, but not as pretty. I believe it is functionally equivalent to:
l = list() for i,j in object: l.append(function(i,j))
or even better use map:
map(function, object)
But of course function would have to get i
, j
itself.
Isn't this the same question as 3?
You can use two for loops in same line by using zip
function
Code:
list1 = ['Abbas', 'Ali', 'Usman']
list2 = ['Kamran', 'Asgar', 'Hamza', 'Umer']
list3 = []
for i,j in zip(list1,list2):
list3.append(i)
list3.append(j)
print(list3)
Output:
['Abbas', 'Kamran', 'Ali', 'Asgar', 'Usman', 'Hamza']
So, by using zip function, we can use two for loops or we can iterate two lists in same row.
Below code for best examples for nested loops, while using two for loops please remember the output of the first loop is input for the second loop. Loop termination also important while using the nested loops
for x in range(1, 10, 1):
for y in range(1,x):
print y,
print
OutPut :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
Source: Stackoverflow.com