1

I am wondering if I can iterate over a list of lists with another list in python:

let's say

lst_a = [x,y,z]  
lst_b = [[a,b,c,d],[e,f,g,h],[i,j,k,l]] 

where len(lst_a) = len(lst_b)

I am wondering how to get a new list like below:

lst_c = [[x/a, x/b, x/c, x/d],[y/e, y/f, y/g, y/h],[z/i, z/j, z/k, z/l]]

thanks a lot!

tim

3 Answers 3

5

You can use a nested list comprehension

>>> lst_a = [1,2,3]
>>> lst_b = [[1,2,3,4],[2,3,4,5],[3,4,5,6]]
>>> lst_c = [[i/b for b in j] for i,j in zip(lst_a, lst_b)]
>>> lst_c
[[1.0, 0.5, 0.3333333333333333, 0.25], [1.0, 0.6666666666666666, 0.5, 0.4], [1.0, 0.75, 0.6, 0.5]]
Sign up to request clarification or add additional context in comments.

2 Comments

would you happen to know where i might look for more info so as to learn nested list comprehension better?
This page seems to be pretty thorough. Don't worry about the nesting just yet, just read the page to understand the list comprehension, then you'll see the nesting is just one step past that.
0
lst_a = [x,y,z]  
lst_b = [[a,b,c,d],[e,f,g,h],[i,j,k,l]] 
lst_c = []

for i in range(len(lst_a)):
    lst_c.append([lst_a[i]/lst_b[i][0]])
    for j in range(1, len(lst_b[i])):
        lst_c[i].append(lst_a[i]/lst_b[i][j])

Comments

0

You can do this using numpy.

import numpy

lst_a = [x,y,z]  
lst_b = [[a,b,c,d],[e,f,g,h],[i,j,k,l]] 
new_list = []

for i, item in enumerate(lst_a):
   new_list_i = float(lst_a[i])/numpy.array(lst_b[i])
   new_list.append(new_list_i.tolist())

print new_list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.